How to Send an Email Using Python Code
The ability to send emails automatically can be very useful in various situations.
For example, you can process crawled data and send reports at scheduled times, or automatically send alert emails when specific events occur.
In this lesson, we will learn how to send a simple email using Python's smtplib library.
Simple Email Sending Code Example
Below is a simple example of sending an email using smtplib.
# Importing the smtplib library
import smtplib
# Importing libraries for email composition
from email.mime.text import MIMEText
# Importing libraries for composing email body and subject
from email.mime.multipart import MIMEMultipart
# Setting up the sender's information
sender_email = "your_email@example.com"
password = "your_password"
# Setting up the receiver's information
receiver_email = "receiver@example.com"
# Writing the email subject and body
subject = "Test Email"
body = "Hello, this is a test email sent using Python's smtplib."
# Setting up MIME
msg = MIMEMultipart()
# Sender
msg['From'] = sender_email
# Receiver
msg['To'] = receiver_email
# Subject
msg['Subject'] = subject
# Adding the body
msg.attach(MIMEText(body, 'plain'))
# Connecting to the SMTP server and sending the email
try:
# Setting up SMTP server and port number
server = smtplib.SMTP('smtp.example.com', 587)
# Starting TLS security
server.starttls()
# Logging in
server.login(sender_email, password)
# Sending the email
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error occurred while sending email: {e}")
finally:
server.quit() # Disconnecting from the server
Detailed Code Explanation
1. Setting up Sender and Receiver Information
At the beginning of the code, you set up the sender and receiver email addresses, and the sender's email account password.
The sender's email and password are used to connect to the SMTP server to send the email.
sender_email = "your_email@example.com"
receiver_email = "receiver@example.com"
password = "your_password"
2. Writing the Email Subject and Body
You write the email's subject (subject
) and body (body
).
The body is composed of simple text, which is converted to a MIMEText
object and attached to the email.
subject = "Test Email"
body = "Hello, this is a test email sent using Python's smtplib."
After that, you use a MIMEMultipart
object to bundle the email's subject, body, sender, and receiver together.
# The container for the email message
msg = MIMEMultipart()
# Setting up the sender
msg['From'] = sender_email
# Setting up the receiver
msg['To'] = receiver_email
# Setting up the email subject
msg['Subject'] = subject
# Adding the email body
msg.attach(MIMEText(body, 'plain'))
In this code, the MIMEMultipart
object bundles various parts of the email (e.g., subject, body, attachments, etc.) together.
The MIMEText
object represents the email's body as text, and the 'plain'
argument indicates that the text format is plain text.
3. Connecting to the SMTP Server and Sending the Email
Connecting to the SMTP Server
SMTP('smtp.example.com', 587)
connects to an external SMTP server.
Here, 587
is the port number for the SMTP server, which is used to send the email.
Port
: A number used by programs to communicate in a network
What is TLS?
After setting up the connection to the SMTP server, the security is enhanced with TLS (Transport Layer Security).
TLS is a protocol that encrypts emails, enhancing security to prevent sensitive information from being exposed during email transmission.
The sender logs into the server with their email account, and then uses the sendmail
method to send the email.
After completing all actions, the server connection is terminated.
# Connecting to the SMTP server
server = smtplib.SMTP('smtp.example.com', 587)
# Starting TLS security
server.starttls()
# Logging in with the sender's account
server.login(sender_email, password)
# Sending the email
server.sendmail(sender_email, receiver_email, msg.as_string())
Practice
In the practice code in the code editor, input your subscribed CodeFriends email to receiver_email
or check if it is well reflected, and then run the code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.