Blog

Three Ways to Send Emails Using Python With Code Tutorials

Milan BhardwajMilan BhardwajMarch 04, 2021
How to Send Email Using Python Header

You can send email from Python three ways: the built-in smtplib module over SMTP, a transactional email API like SendGrid, or a multichannel notification service like Courier that sits on top of your email provider. smtplib needs no installs, an email API adds deliverability and delivery events, and Courier adds templates, logs, and other channels without changing your send code.

You can send email from Python for all kinds of reasons: alert yourself when something breaks in production, confirm a new user's signup, or tell users about new activity in your app.

3 ways to send emails from your Python app

There are three main options for sending email with Python: SMTP, a transactional email service, and a multichannel notification service. Each one gets a code tutorial below, and every snippet runs on Python 3.9 or newer.

1. Using SMTP

Python has a built-in module for sending email over SMTP, so you can send your first email without installing anything. It works with any mail server that speaks SMTP.

The tradeoffs show up as you grow. A mailbox like Gmail has a daily cap (Google lists 2,000 messages a day for the Gmail SMTP server on Workspace) and isn't built for bulk sending. SMTP also gives you no delivery events: the server accepting your message doesn't mean it reached the inbox, and bounces come back as emails you have to parse yourself. Retries, deliverability, and uptime are yours to own.

2. Using a transactional email service

You can also send through a hosted transactional email API like SendGrid, Mailgun, or Amazon SES. These services run the sending infrastructure for you: they manage sender reputation, handle bounces, and report what happened to each email. Most of them ship a Python SDK.

The cost is a new API to learn and a dependency on one vendor. If you switch providers later, you rewrite the integration and usually your templates too. An email API also covers only email, so adding SMS or push means another vendor and another integration.

3. Using a multichannel notification service

If you plan to notify users on more than one channel, use a multichannel notification service. Courier, for example, gives you one API to notify users over email, SMS, push, in-app, and chat apps like Slack and WhatsApp. You design templates in Design Studio, a drag-and-drop editor, and see every message's delivery timeline in Logs.

Even if you only send email today, it pays off when your needs change. Courier sits on top of your email provider (SMTP or an email API), so you can switch providers, add a backup provider for automatic failover, or add channels without changing your send code.

The tradeoff: Courier still delivers through an email provider, so you depend on two services instead of one. Failover across providers offsets some of that risk.

Tutorial: How to send emails using SMTP in Python

Python's built-in smtplib module sends email over SMTP (Simple Mail Transfer Protocol), which is defined in RFC 5321. The email.message module builds the message itself. This walkthrough uses Gmail's SMTP server, smtp.gmail.com.

1. Turn on 2-Step Verification for the Google account you'll send from, then create an app password. Google turned off less secure app access for all Google accounts on March 14, 2025, so your regular account password no longer works over SMTP. The app password takes its place. If you don't see the option to create one, Google lists the usual causes: a work or school account, 2-Step Verification set up with security keys only, or Advanced Protection. In those cases, use OAuth instead.

2. Store your address and app password in environment variables so they stay out of your code:

Terminal
export GMAIL_ADDRESS="your_email@gmail.com"
export GMAIL_APP_PASSWORD="your-app-password"

3. Import smtplib. It ships with Python, so create a Python file and import it, along with EmailMessage to build the email.

4. To create a secure connection, you can either use SMTP_SSL() on port 465 or .starttls() on port 587. The former creates an SMTP connection that's encrypted from the start. The latter opens an unencrypted connection and upgrades it to TLS with .starttls().

To send email through SMTP_SSL():

Python
import os
import smtplib
import ssl
from email.message import EmailMessage

gmail_user = os.environ["GMAIL_ADDRESS"]
app_password = os.environ["GMAIL_APP_PASSWORD"]

msg = EmailMessage()
msg["From"] = gmail_user
msg["To"] = "person_a@example.com, person_b@example.com"
msg["Subject"] = "Your account is active"
msg.set_content("Thanks for signing up. Your account is ready to use.")

context = ssl.create_default_context()

try:
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(gmail_user, app_password)
        server.send_message(msg)
    print("Email sent")
except smtplib.SMTPException as ex:
    print("Something went wrong:", ex)

To send email through .starttls():

Python
import os
import smtplib
import ssl
from email.message import EmailMessage

gmail_user = os.environ["GMAIL_ADDRESS"]
app_password = os.environ["GMAIL_APP_PASSWORD"]

msg = EmailMessage()
msg["From"] = gmail_user
msg["To"] = "person_a@example.com"
msg["Subject"] = "Your account is active"
msg.set_content("Thanks for signing up. Your account is ready to use.")

context = ssl.create_default_context()

try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls(context=context)  # Upgrade the connection to TLS
        server.login(gmail_user, app_password)
        server.send_message(msg)
    print("Email sent")
except smtplib.SMTPException as ex:
    print("Something went wrong:", ex)

EmailMessage sets the headers and encoding for you, and send_message() reads the sender and recipients from those headers. To send HTML, call msg.add_alternative(html, subtype="html") after set_content(), and the plain-text version becomes the fallback.

Tutorial: How to send emails using a transactional email service in Python

If you send a high volume of transactional emails or need better deliverability, use a transactional email service. There are many to choose from, including Amazon SES, Mailgun, and Postmark, and most of them have a Python SDK.

This tutorial uses SendGrid, one of the most popular email APIs. SendGrid no longer has a free plan, but its 60-day trial lets you send 100 emails a day.

1. Create an account with SendGrid.

2. Create an API key: go to Settings > API Keys and click Create API Key. Name the key, choose Custom Access and give it full access to Mail Send (or choose Full Access), then click Create & View. SendGrid shows the key only once, so copy it now.

3. Verify the address you'll send from by creating a sender identity under Settings > Sender Authentication. SendGrid only sends from verified senders.

4. Install the SendGrid Python SDK:

Terminal
pip install sendgrid

5. Set your API key as an environment variable:

Terminal
export SENDGRID_API_KEY="<SENDGRID_API_KEY>"

6. Create a Python script that builds the email and sends it:

Python
import os

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email="you@example.com",  # Change to your verified sender
    to_emails="recipient@example.com",  # Change to your recipient
    subject="Your account is active",
    html_content="<strong>Thanks for signing up.</strong> Your account is ready to use.",
)

try:
    sg = SendGridAPIClient(os.environ["SENDGRID_API_KEY"])
    response = sg.send(message)
    print("Email sent, status:", response.status_code)
except Exception as ex:
    print("Something went wrong:", ex)

A 202 status means SendGrid accepted the email for delivery. To see whether it was delivered and opened, open Activity in the SendGrid console.

Tutorial: How to send emails using a multichannel notification service in Python

If you want to scale your app's notifications while keeping your codebase clean, use a multichannel notification service like Courier. Courier works with your own email provider, including SMTP, Gmail, and email APIs like SendGrid, Amazon SES, and Postmark.

1. Sign up for Courier. The Developer plan includes 10,000 messages a month free. Copy your Test key from Settings → API Keys and set it as an environment variable:

Terminal
export COURIER_API_KEY="<YOUR_TEST_API_KEY>"

Every Test environment comes with the Courier Test Email Provider, which delivers to your signup address only. To email anyone else, connect your own provider. If you want to send from your Gmail account without running SMTP, connect the Gmail integration: Courier sends through the Gmail API with OAuth. Google's daily limits still apply, so keep Gmail for testing and small internal sends.

2. Install the Courier Python SDK. The package is trycourier, and you import it as courier:

Terminal
pip install trycourier

Send a first email with inline content to check your setup. Use the address you signed up with as the recipient:

Python
from courier import Courier

client = Courier()  # Reads COURIER_API_KEY from your environment

response = client.send.message(
    message={
        "to": {"email": "you@example.com"},  # The address you signed up with
        "content": {
            "version": "2022-01-01",
            "elements": [
                {"type": "meta", "title": "Hello from Courier!"},
                {
                    "type": "html",
                    "content": "<h1>It works!</h1><p>You sent this from Python.</p>",
                },
            ],
        },
    },
)

print("Sent, request ID:", response.request_id)

The meta element's title becomes the subject line. The call returns a request_id. To check on the email, open Logs in the Courier console: it lists every message in the current environment, newest first, with a timeline for each one.

3. Design and preview your email in Courier

Inline content is fine for a test. For real emails, design a template in Courier, so you or anyone working on your app can change the content without shipping more code. For this tutorial, you'll create an account activation email.

Use the visual editor to design your email

Open Templates, select Add template, and choose Design Studio v2. Select the Email channel tab, and use the routing selector in the toolbar to pick the provider that delivers it. Then drag in blocks like Text, Button, Image, and Divider to compose your email. Courier auto-saves as you edit.

Add variables with double braces and a namespace prefix. For the activation email, write Hi {{data.username}}, your account is active as of {{data.date}}. Fields on the recipient's profile work the same way, like {{profile.email}}. See variables for the full list.

Customize your brand

Apply a Brand from the toolbar to add your logo, colors, header, and footer. Every workspace has a default Brand, and every send from a template inherits the Brand you attach to it. If you send white-labeled emails, you can create more than one Brand.

Preview your email

Select Preview & Test and create a test event. Fill the data and profile objects with values for your variables:

JSON
{
  "data": { "username": "ada", "date": "March 4, 2026" },
  "profile": { "email": "you@example.com" }
}

The preview renders your email with that data. A variable that still shows as raw {{...}} doesn't match a path in your test event. Send Test delivers a live copy to yourself.

Publish your email

Select Publish. Edits stay in the draft until you publish. Then copy the Template ID from the top of the editor.

4. Send the template from your Python app:

Python
from courier import Courier

client = Courier()

response = client.send.message(
    message={
        "to": {"email": "you@example.com"},
        "template": "<TEMPLATE_ID>",  # From the top of the Design Studio editor
        "data": {
            "username": "ada",
            "date": "March 4, 2026",
        },
    },
)

print("Sent, request ID:", response.request_id)

The message object has three fields here:

  • to: the recipient. Use {"email": ...} to send to an address, or {"user_id": ...} to send to a user whose profile you've stored in Courier.
  • template: the Template ID you copied.
  • data: the values for your template variables. username fills {{data.username}}.

When you're ready to go live, create a Production API key and connect your email provider in Production. Test and Production are isolated, with separate keys, templates, integrations, and logs. See environments for details.

How to send emails with attachments in Python

With smtplib, add the file to your EmailMessage before you send it. Put this after set_content() in either SMTP script above, and add from pathlib import Path to the imports:

Python
msg.add_attachment(
    Path("invoice.pdf").read_bytes(),
    maintype="application",
    subtype="pdf",
    filename="invoice.pdf",
)

With Courier, attachments go in a provider override, because each email provider expects its own attachment format. This example attaches a PDF when SendGrid is your email provider in Courier. The file content is base64 encoded:

Python
import base64

from courier import Courier

client = Courier()

with open("invoice.pdf", "rb") as f:
    encoded = base64.b64encode(f.read()).decode()

response = client.send.message(
    message={
        "to": {"email": "user@example.com"},
        "template": "<TEMPLATE_ID>",
        "data": {"username": "ada"},
        "providers": {
            "sendgrid": {
                "override": {
                    "body": {
                        "attachments": [
                            {
                                "content": encoded,
                                "type": "application/pdf",
                                "filename": "invoice.pdf",
                            },
                        ],
                    },
                },
            },
        },
    },
)

print("Sent, request ID:", response.request_id)

With Courier's SMTP integration, the override goes under providers.smtp and uses Nodemailer's fields (filename, content, encoding, contentType). Each provider's integration page shows its schema, and email channel overrides lists the fields every email provider takes.

Wrapping it up

You now have three ways to send email from Python: smtplib with a Gmail app password, the SendGrid Python SDK, and the Courier Python SDK. If you send a handful of emails, SMTP gets you there with no dependencies. If you need volume and deliverability, use an email API. If you expect to add channels, or want teammates to edit content without a deploy, Courier sits on top of your email provider and adds them through the same API.

Author: Milan Bhardwaj