How to Send Emails Using Python [Step-by-Step Guide]

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:

  1. Set up an SMTP server and authenticate
  2. Create the email message
  3. 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:

  1. Enable 2-step verification in your Gmail account settings
  2. Generate an app password for your Python script
  3. 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.

How to Send Emails Using Python

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:

  1. Set up an SMTP server and authenticate using Gmail’s SMTP server
  2. Create an email message using the email library
  3. Send the email using smtplib
  4. Add file attachments to your email messages
  5. 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 email library’s MIMEMultipart and MIMEText classes
  • Attach files using the MIMEBase class 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 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.