In this tutorial, I will explain how to send emails using Python. Sending emails programmatically can be incredibly useful for automating notifications, reports, and other communications. Python provides built-in libraries that make it easy to compose and send emails. I’ll walk you through the process step-by-step, providing code examples.
First, let’s look at the basic steps involved in sending an email with Python:
- Set up an SMTP server and authenticate
- Create the email message
- Send the email
Set up an SMTP Server
To send emails using Python, you’ll need access to an SMTP (Simple Mail Transfer Protocol) server. If you’re using a Gmail account, you can use Gmail’s SMTP server. Here’s how to set it up:
- Enable 2-step verification in your Gmail account settings
- Generate an app password for your Python script
- Use the following SMTP settings:
- Server: smtp.gmail.com
- Port: 587
- Username: your Gmail address
- Password: the app password you generated
Here’s an example of how to establish a connection to Gmail’s SMTP server using Python’s built-in smtplib library:
import smtplib
smtp_server = 'smtp.gmail.com'
port = 587
sender_email = 'john.doe@gmail.com'
password = 'your_app_password'
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)Check out Access Modifiers in Python
Create the Email Message
Next, you’ll need to compose your email message. Python’s built-in email library provides classes for creating email messages, including MIMEMultipart for multi-part messages and MIMEText for plain text.
Here’s an example of creating a basic email message:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = 'jane.smith@example.com'
message['Subject'] = 'Test Email'
body = 'This is a test email sent from Python.'
message.attach(MIMEText(body, 'plain'))You can also send HTML-formatted emails by specifying 'html' instead of 'plain' when attaching the message body.

Send the Email
Finally, you can send the email using the send_message method of the SMTP server object:
server.send_message(message)
server.quit()Here’s the complete code for sending a basic email in Python.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtp_server = 'smtp.gmail.com'
port = 587
sender_email = 'john.doe@gmail.com'
password = 'your_app_password'
receiver_email = 'jane.smith@example.com'
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Test Email'
body = 'This is a test email sent from Python.'
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)
server.send_message(message)
server.quit()Now, let me show you one more important thing: how to send attachments while sending an email in Python.
Read Declare and Use Tuples in Python
Add Attachments to Email
You can also attach files to your email messages, such as PDFs, images, or any other file type. To do this, you’ll need to use the MIMEBase class from the email.mime.base module.
Here’s an example of attaching a PDF file to an email:
from email.mime.base import MIMEBase
from email import encoders
filename = 'document.pdf'
with open(filename, 'rb') as attachment:
mimetype = 'application/pdf'
attachment_name = 'document.pdf'
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f'attachment; filename= {attachment_name}',
)
message.attach(part)This code reads the PDF file in binary mode, creates a MIMEBase object with the appropriate MIME type and file name, encodes the file data using base64, and attaches it to the email message.
Read Best Programming Languages for Machine Learning
Handle Errors and Exceptions
When sending emails, it’s important to handle potential errors and exceptions gracefully. Some common issues you might encounter include:
- Authentication errors (invalid username or password)
- Connection errors (SMTP server unavailable or timeout)
- Recipient errors (invalid email address)
You can use a try/except block to catch and handle these exceptions. Here’s an example:
try:
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)
server.send_message(message)
except smtplib.SMTPAuthenticationError:
print('Authentication failed. Check your username and password.')
except smtplib.SMTPConnectError:
print('Failed to connect to the SMTP server.')
except smtplib.SMTPRecipientsRefused:
print('One or more recipients were rejected.')
except Exception as e:
print(f'An error occurred: {e}')
finally:
server.quit()Conclusion
In this tutorial, I’ve covered the basics of sending emails using Python. We’ve looked at how to:
- Set up an SMTP server and authenticate using Gmail’s SMTP server
- Create an email message using the
emaillibrary - Send the email using
smtplib - Add file attachments to your email messages
- Handle common errors and exceptions
With these techniques, you can automate email sending for a variety of purposes, such as sending notifications, reports, or marketing campaigns.
Some key takeaways:
- Use an app password when authenticating with Gmail’s SMTP server
- Compose your email messages using the
emaillibrary’sMIMEMultipartandMIMETextclasses - Attach files using the
MIMEBaseclass and base64 encoding - Always handle exceptions and gracefully close the SMTP connection
I hope this guide has helped get you started with sending emails using Python. Do let me know in the comment below if it works for you.
You may also like:
- 51 Machine Learning Interview Questions and Answers
- Why Is Python Used for Machine Learning?
- Percentage Symbol (%) in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.