目次
1. Introduction
Sending email with Python is a very useful skill for both personal applications and business systems. For example, it can be used to automatically send notifications to users from an application or to deliver system error logs to administrators in real time. Also, by sending mail via code instead of manually, you can efficiently handle email delivery and greatly streamline everyday tasks. Python includes “smtplib” in its standard library, allowing basic email sending without adding external modules. In this article, we explain the basic setup and steps for sending email with Python and introduce practical methods using real code examples. We also cover advanced topics in detail, such as HTML-formatted emails, sending emails with attachments, Gmail security settings, sending emails in Japanese, and bulk sending to multiple recipients. By the end of this guide, you’ll be able to send emails with Python easily and will have the knowledge to apply it in a variety of situations.2. How to Send Email with Python
To send email with Python, use the standard library “smtplib”. This library lets you send email through an SMTP server simply by writing code. Below we provide a detailed overview of the smtplib module and the basic steps for sending email.Introduction to the smtplib module
The smtplib module is part of Python’s standard library and supports the SMTP client protocol. Using this module, you can connect directly to an SMTP server from Python and send email.Key features of smtplib
- Easily communicates with SMTP servers.
- No extra external modules are required; it’s included with Python, so no additional setup is needed.
- Supports security settings and error handling.
Basic steps for sending email
Now we’ll walk through the basic steps for sending email with Python. By following the steps below, you can send email easily.1. How to connect to an SMTP server
First, you need to connect to an SMTP server. This is the starting point for sending email. Generally, you’ll often use SMTP servers provided by services like Gmail, Yahoo Mail, or Outlook, but it’s also possible to use a company’s dedicated SMTP server.import smtplib
# SMTP server settings
smtp_server = "smtp.example.com" # Example: For Gmail, use "smtp.gmail.com"
smtp_port = 587 # Common port number. For Gmail, use 587
2. Setting up login authentication
After establishing a connection to the SMTP server, log in with the sender’s email address and password. When using services like Gmail, additional security settings may be required.# Email account information
username = "your_email@example.com"
password = "your_password"
# Connect and log in to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Establish a secure connection
server.login(username, password)
3. Creating and sending the email
Next, create the content of the email to be sent. Specify the recipient address, subject, and body, and send it through the SMTP server.# Email sending information
to_address = "recipient@example.com"
subject = "Test email"
body = "This email was sent from Python."
# Email format
message = f"Subject: {subject}
{body}"
# Send email
server.sendmail(username, to_address, message)
print("Email has been sent!")
4. Key points for error handling
Connections to the SMTP server and sending email can produce unexpected errors. For that reason, use try-except blocks so you can handle errors appropriately.try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message)
print("The email was sent successfully!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit() # Close the connection
Summary
This covers the basic procedure for sending email with Python. Once you learn this flow, you can automate emails, send multiple messages at once, and apply it in various ways. In the next section, we’ll look in detail at sending plain text emails, HTML emails, and emails with attachments using actual code examples.
3. Practical: Email Sending Code Examples in Python
From here, we’ll present actual code examples for sending email using Python. We’ll explain step by step how to send plain text emails, HTML emails, and emails with attachments.Sending Plain Text Emails
First, here’s how to send the most basic form: a plain text email. We’ll use the smtplib module to send a simple text message.Code Example
import smtplib
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "Plain text email test"
body = "This is a plain text email sent from Python."
# Email format
message = f"Subject: {subject}
{body}"
try:
# Connect to the server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message)
print("Plain text email sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
Sending HTML Emails
Next, we’ll explain how to send HTML-formatted emails. Using HTML emails lets you style the body and embed links. When including HTML code in the email body, use the email.mime module to handle the HTML correctly.Code Example
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "HTML email test"
html_content = '''
<html>
<body>
<h1>Hello</h1>
<p>This is an HTML-formatted email sent from <strong>Python</strong>.</p>
<a href="https://example.com">Click here</a>
</body>
</html>
'''
# Create the email
message = MIMEMultipart()
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
message.attach(MIMEText(html_content, "html"))
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("HTML email sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
Sending Emails with Attachments
Next, we’ll show how to send emails with files attached. For example, you can attach PDFs or images to your email. This uses the MIMEBase class from the email.mime module.Code Example
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Email account information
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your_email@example.com"
password = "your_password"
# Recipient and contents
to_address = "recipient@example.com"
subject = "Test email with attachment"
body = "I have attached a file. Please check it."
# Create the email
message = MIMEMultipart()
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# Attach file
filename = "example.pdf" # Name of the file to attach
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={filename}")
message.attach(part)
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("Email with attachment sent!")
except Exception as e:
print("Email send error:", e)
finally:
server.quit()
Summary
By using the code examples above, you can send various types of email with Python. Depending on your needs, you can choose between plain text, HTML, or emails with attachments. In the next section, we’ll use Gmail as an example to explain specific settings and precautions when using a particular SMTP server.4. Sending email with Gmail
This section explains in detail how to send email with Gmail using Python. Gmail is widely used and provides an SMTP server that Python programs can easily access. However, sending mail through Gmail requires a few security settings.Gmail SMTP settings
To send mail using Gmail, use the following SMTP server information:- SMTP server:
smtp.gmail.com
- Port: 587 (use TLS) or 465 (use SSL)
- Authentication: Required
Basic setup code example
import smtplib
from email.mime.text import MIMEText
# Gmail SMTP server settings
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_password"
# Recipient and content
to_address = "recipient@example.com"
subject = "Test email from Gmail"
body = "This email was sent through Gmail from Python."
# Create the email content
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
# Connect to the server and send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Use TLS to enhance security
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("The email was sent using Gmail!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
Security considerations
When using a Gmail account, you should review your security settings. Gmail typically imposes security restrictions on access from third-party applications. Therefore, when accessing from Python, the following steps are necessary.Obtaining an app password
- Enable two-factor authentication: Turn on 2-Step Verification in your Gmail account settings. This will allow an app password to be generated.
- Generate an app password: From Gmail’s Account settings > Security > App passwords, generate a dedicated app password for your Python program. This password is used in place of your regular login password.
Notes
- Managing app passwords: Keep app passwords strictly confidential and secure.
- Account security: Using app passwords is recommended to help prevent unauthorized access to your Gmail account.
Code example (using an app password)
When using an app password, the code looks like this.import smtplib
from email.mime.text import MIMEText
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
app_password = "your_app_password" # Use an app password instead of your regular password
to_address = "recipient@example.com"
subject = "Test email from Gmail using an app password"
body = "This email was sent from Gmail using an app password."
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, app_password)
server.sendmail(username, to_address, message.as_string())
print("The email was sent using Gmail!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
Summary
When sending email from Python via Gmail, your account’s security settings are important. Using an app password allows you to send email more securely. The next section will introduce advanced email-sending techniques in Python, including sending to multiple recipients, scheduled automated sending, and how to send emails in Japanese.
5. Advanced Applications: Email Sending Techniques
From here, we’ll cover advanced email-sending techniques in Python. This section explains practical methods such as bulk sending to multiple recipients, automating scheduled emails, and sending emails in Japanese.Sending to Multiple Recipients
With Python, you can send a message to multiple recipients at once. By properly setting the email’s “To”, “Cc”, and “Bcc” fields and managing recipients as a list, bulk sending becomes simple.Code example
Below is a code example that specifies multiple recipients in the “To” field.import smtplib
from email.mime.text import MIMEText
# SMTP server info
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
# Recipient list
to_addresses = ["recipient1@example.com", "recipient2@example.com"]
subject = "Test email to multiple recipients"
body = "This email was sent to multiple recipients at once."
# Create the email
message = MIMEText(body)
message["From"] = username
message["To"] = ", ".join(to_addresses) # Separate multiple recipients with commas
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_addresses, message.as_string())
print("The email to multiple recipients has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
Automating Scheduled Email Sending
To send emails periodically, setting up a schedule is useful. Python has libraries such as “schedule” and the “time” module to run recurring tasks based on time intervals. For example, you can assemble a script to automatically send emails at a specific time.Code example (Scheduled sending using schedule)
import smtplib
from email.mime.text import MIMEText
import schedule
import time
def send_email():
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
to_address = "recipient@example.com"
subject = "Scheduled email"
body = "This is an email sent on a regular schedule."
message = MIMEText(body)
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("Email has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
# Send the email every day at 9:00 AM
schedule.every().day.at("09:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
This script will automatically send an email every day at the specified time (here, 9:00 AM).Sending Emails in Japanese
When sending emails in Japanese with Python, you need to pay attention to encoding. Especially for subjects and bodies that include Japanese, configure your messages to use UTF-8 encoding to ensure correct transmission.Code example (Japanese support)
import smtplib
from email.mime.text import MIMEText
from email.header import Header
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your_email@gmail.com"
password = "your_app_password"
to_address = "recipient@example.com"
# Japanese subject and body
subject = Header("Test email in Japanese", "utf-8")
body = "This is an email sent in Japanese from Python."
message = MIMEText(body, "plain", "utf-8")
message["From"] = username
message["To"] = to_address
message["Subject"] = subject
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(username, to_address, message.as_string())
print("The Japanese email has been sent!")
except Exception as e:
print("Email sending error:", e)
finally:
server.quit()
Summary
In this section, we’ve covered advanced email-sending techniques in Python. Using features such as sending to multiple recipients, automating scheduled emails, and supporting Japanese makes your email sending more practical. The next section will summarize the article and review the key points.6. Summary
This article walked through how to send email with Python, from basics to advanced techniques. By using Python’s standard library “smtplib”, sending email becomes simple and can be applied to everyday tasks and applications. Below is a recap of the key points learned in each section.- Basic steps for sending email
- You learned how to use Python’s “smtplib” module to send email through an SMTP server.
- We also covered the workflow from composing to sending emails and the importance of error handling.
- Practical email sending code examples
- We introduced how to send plain text emails, HTML emails, and emails with attachments, each with code examples.
- This enabled you to adapt code to different email formats to meet various needs.
- Sending email with Gmail
- We explained Gmail’s SMTP server settings and security measures using app passwords.
- We reiterated that when using a Gmail account, you need to enable two-step verification and set up an app password.
- Advanced email sending techniques
- We covered sending to multiple recipients, automating scheduled emails, and techniques for handling Japanese-language content.
- In particular, we emphasized that proper encoding settings are important when sending emails that include Japanese in the subject or body.