Site icon The Brand Hopper

How to Send Email in Python: SMTP & API Methods Explained

How to Send Email in Python

Virtually every business uses email as a communication tool. Sending emails from applications you build as a developer is something you will often need to do. With Python’s SMTP support and email API libraries, this is easy.

In this guide, we’ll show you how to send emails using Python code in multiple ways. We’ll cover the basics of SMTP, then go on to more advanced options with email APIs like SendGrid and Mailgun.

Overview: Sending Email from Python Code

Here are the main ways to send email with Python:

SMTP – The Simple Mail Transfer Protocol (SMTP) is the standard protocol for sending email on the internet. The SMTP-capable module built into Python makes it very easy to add email capabilities to your code.

Email Service Provider APIs – Email services for developers, like UniOne, SendGrid, Mailgun, SparkPost, etc., provide easy-to-use email API libraries for Python to send bulk and transactional emails at scale. Deliverability and reputation management are handled by the service for you.

Gmail API – Access your Gmail account securely with Python code and Google’s Gmail API. It’s useful if you want to send emails using an existing Gmail account.

In this guide, we will look at code samples using each method. At the end of this SMTP API service guide, you should know how to add email functionality to Python apps and scripts.

Sending Email with Python’s SMTP Library

The smtplib library is part of the Python installation package for sending mail using the SMTP protocol.

Here’s how to send a basic SMTP email in Python, using Google’s SMTP server. For any other server, the code will be very similar, with different values for host, username and password.

import os

import smtplib

from email.message import EmailMessage

email = EmailMessage()

email[‘from’] = ‘John Smith <john.smith@example.com>’

email[‘to’] = ‘mary.jones@example.com’

email[‘subject’] = ‘Test Email’

email.set_content(‘Body of the email’)

with smtplib.SMTP(host=’smtp.gmail.com’, port=587) as smtp:

smtp.ehlo()

smtp.starttls()

smtp.login(‘john.smith@gmail.com’,

os.getenv(“EMAIL_PASSWORD”))

smtp.send_message(email)

print(‘Email sent!’)

Let’s break this down section by section.

Import Libraries

We import smtplib for the SMTP protocol functions and email.message to construct the email object:

import smtplib

from email.message import EmailMessage

Construct Email Message

Create an EmailMessage instance and set the from, to, and subject headers: 

email = EmailMessage()

email[‘from’] = ‘John Smith <john.smith@example.com>’

email[‘to’] = ‘mary.jones@example.com’

email[‘subject’] = ‘Test Email’

Add the email body: 

email.set_content(‘Body of the email’)

Send with SMTP Server

Open an SMTP connection to your chosen mail server and send email Python style:

with smtplib.SMTP(host=’smtp.gmail.com’, port=587) as smtp:

smtp.ehlo()

smtp.starttls()

smtp.login(‘john.smith@google.com’,

os.getenv(“EMAIL_PASSWORD”))

smtp.send_message(email)

print(‘Email sent!’)

Here, you log in to Google’s SMTP server using your email address as username. The password, stored in the EMAIL_PASSWORD environment variable for added security, is to be obtained separately using the procedure described here.

This example demonstrates how to send an email with Python using the built-in SMTP library and Google’s SMTP server. It is one of the most straightforward approaches to Python send email tasks. However, remember that you are limited to sending just 100 emails per day.

Now, let’s look at how to do the same using other public SMTP servers.

Sending Through Yahoo’s SMTP Server

Here are the settings for sending emails with Python through Yahoo’s SMTP server:

SMTP_SERVER = “smtp.mail.yahoo.com”

SMTP_PORT = 587

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:

server.starttls()

server.login(“youremail@yahoo.com”, os.getenv(“YAHOO_PASSWORD”))

server.send_message(…)

Key things to note for Yahoo Mail:

  • Use SMTP server smtp.mail.yahoo.com
  • Enable TLS encryption
  • Login with your Yahoo username and password

Yahoo also has low sending limits, so it’s better used for low-volume email.

Sending Through Outlook.com’s SMTP Server

To send emails with Python through Outlook.com’s SMTP server:

SMTP_SERVER = “smtp-mail.outlook.com”

SMTP_PORT = 587

with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:

server.ehlo()

server.starttls()

server.login(“youremail@outlook.com”, os.getenv(“OUTLOOK_PASSWORD”))

server.send_message(…)

For Outlook.com

  • Use SMTP server smtp-mail.outlook.com
  • Enable TLS with starttls()
  • Log in with your Outlook.com credentials

Outlook.com has good deliverability but lower sending limits than dedicated email providers.

Sending Email via Mailgun’s API

Mailgun is a popular email service provider with a generous free tier for low-volume email. Here’s how to integrate it using Python’s requests library:

import requests

mg_api_key = ‘YOUR_API_KEY’

mg_domain = ‘YOUR_DOMAIN’

response = requests.post(

f”https://api.mailgun.net/v3/{mg_domain}/messages”,

auth=(“api”, mg_api_key),

data={

“from”: “Excited User <mailgun@YOUR_DOMAIN>”,

“to”: [“mary@example.com”],

“subject”: “Hello from Mailgun”,

“text”: “This email was sent using Mailgun API in Python!”

}

)

print(response.status_code, response.json())

Mailgun has a free plan with 100 daily messages, which is enough for getting started.

Sending Bulk Email via SendGrid’s API

SendGrid is another popular email service focused on transactional and bulk email delivery.

from sendgrid import SendGridAPIClient

from sendgrid.helpers.mail import Mail

message = Mail(

from_email=’test@example.com’,

to_emails=’mary@example.com’,

subject=’Sending with SendGrid’,

plain_text_content=’Hello World from SendGrid!’

)

try:

sg = SendGridAPIClient(‘YOUR_SENDGRID_API_KEY’)

response = sg.send(message)

print(response.status_code)

except Exception as e:

print(str(e))

SendGrid’s free tier allows up to 100 emails per day, making it ideal for testing.

Sending Emails via Gmail API

Gmail API offers another secure way to send email from an existing Gmail account programmatically.

Compared to SMTP, the Gmail API has improved security and anti-abuse control.

To integrate the Gmail API: 

  • Enable Gmail API access for your Google Cloud project
  • Create a service account or OAuth credentials
  • Install the Google client library

from googleapiclient.discovery import build

from google.oauth2.credentials import Credentials

import base64

credentials = Credentials(…)

service = build(‘gmail’, ‘v1’, credentials=credentials)

# Construct message

email_msg = {‘raw’: base64.urlsafe_b64encode(message.as_bytes())}

# Send email

send_status = service.users().messages().send(userId=”me”, body=email_msg).execute()

For complete code samples, see the Gmail API documentation.

The Gmail API is most useful for integrating directly with an existing Gmail account to send email using Python.

Best Practices for Sending Email with Python

Here are some tips for properly sending email with Python:

  • Use a dedicated email provider – Services like SendGrid, UniOne, or Mailgun are meant for sending application emails at scale. They offer built-in monitoring and high deliverability.
  • Handle errors and bounces – Make your script handle errors and bounces from SMTP or API calls. Any time you see a bounce or an issue, you can check return values to match up.
  • Comply with anti-spam laws – When sending commercial mail, know the anti-spam regulations such as CAN-SPAM and CASL. ESP services take care of compliance for you.
  • Use templates – You can pass values into the templates dynamically to quickly create customized mail. Keep HTML and plain text email templates in their own individual files or a database for easier management.
  • Send test emails – Always send test emails and verify the spam score before sending bulk campaigns. MailTester tool can check inbox placement and spam rating.
  • Monitor analytics – Most email API services also have open, click, bounce, etc. analytics, use them to optimize deliverability.

Summary

And there you have it – several ways to easily send email from Python code.

The built-in smtplib library works great for basic SMTP mail. For more advanced use cases, opt for a dedicated email API like UniOne, SendGrid or Mailgun.

You can use the code snippets and best practices covered here as a starting point for adding email capabilities to your own Python projects. Just handle errors and bounces carefully, follow anti-spam rules, and monitor analytics to optimize deliverability over time.

Next Steps

Here are some suggestions for building on these email-sending fundamentals:

  • Add email templates: Separate templates from code for maintainability. Jinja is a popular Python template engine.
  • Expand to bulk email: Move from single emails to bulk sending with dedicated APIs and proper list management.
  • Increase security: Add email authentication mechanisms like SPF, DKIM, and DMARC to improve deliverability and prevent spoofing.
  • Consider alternatives: For SMS, mobile push, and web push notifications, see services like Twilio, Pushover or Pusher.

We hope you found this guide useful! Now, you should understand how to send emails with Python and have a few options to reliably send emails using Python code using either the built-in SMTP library or third-party APIs.

To read more content like this, explore The Brand Hopper

Subscribe to our newsletter

Go to the full page to view and submit the form.

Exit mobile version