Email automation is a common requirement in many applications, from sending notifications to large newsletters. Python offers several options for sending emails, but two of the most commonly used libraries are smtplib and MIMEText. In this blog post, we'll explore these options, set up a virtual environment, install required dependencies, and briefly understand how SMTP works.


Sending emails programmatically can be a vital feature for various applications, such as sending notifications, alerts, or newsletters. Python provides several libraries to accomplish this task efficiently. Among these, and stand out for their simplicity and effectiveness.

Options for Sending Email in Python

There are multiple ways to send emails using Python:

  1. smtplib and email.mime: These standard libraries provide a low-level interface for sending emails using the Simple Mail Transfer Protocol (SMTP).
  2. Flask-Mail/Django Email: These libraries integrate with web frameworks like Flask and Django, providing higher-level abstractions for sending emails.
  3. Third-party services: APIs from services like SendGrid, Mailgun, and Amazon SES can be used for sending emails, offering additional features like analytics and better deliverability.

Why Choose smtplib and MIMEText

and are part of Python's standard library, making them readily available without needing third-party installations. They provide:

  • Simplicity: Easy to use and integrate into any Python script or application.
  • Flexibility: Full control over email contents, headers, and attachments.
  • Reliability: Based on the well-established SMTP protocol, ensuring compatibility with most email servers.

Setting Up a Virtual Environment and Installing Dependencies

Using a virtual environment helps isolate your project's dependencies. Here’s how to set it up:

  1. Create a virtual environment:

  2. Activate the virtual environment:

    • On Windows:
    • On macOS/Linux:
  3. Install necessary dependencies (although and are part of the standard library, you might need additional libraries for more complex emails):

How SMTP Works

SMTP (Simple Mail Transfer Protocol) is a protocol for sending emails across the Internet. It works as follows:

  1. Client-Server Communication: The email client connects to the SMTP server using a protocol like TCP/IP.
  2. Sending Commands: The client sends a series of commands to the server to initiate the email sending process, including authentication.
  3. Transferring Message: The client transfers the email message to the server.
  4. Relaying: The SMTP server relays the email to the recipient's email server, which then delivers it to the recipient’s inbox.

Example code

If you are sending long emails using Python it is best to use when building your message. Here is an example:

First setup your libraries

Code snippet

More resources

If you want to learn more about Python and SMTPlib check out our youtube video playlists.