Development

How to Send Email With Python: SMTP, Gmail API, and SendGrid

ZeroPhantom 2026-02-10 7 min read

Python has multiple ways to send email. Here's a complete reference for every major method with working code.

Method 1 — SMTP with Gmail (Simplest)

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_gmail(to, subject, html_body):
    msg = MIMEMultipart('alternative')
    msg['From'] = 'you@gmail.com'
    msg['To'] = to
    msg['Subject'] = subject
    msg.attach(MIMEText(html_body, 'html'))
    
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
        s.login('you@gmail.com', 'APP_PASSWORD')
        s.send_message(msg)

Requires App Password from Google Account → Security (not your Gmail password).

Method 2 — SendGrid API (Production Scale)

import sendgrid
from sendgrid.helpers.mail import Mail

sg = sendgrid.SendGridAPIClient(api_key='YOUR_KEY')
message = Mail(
    from_email='you@yourdomain.com',
    to_emails='recipient@example.com',
    subject='Hello',
    html_content='

Hello World

' ) sg.send(message)

Method 3 — Microsoft Graph API (Outlook)

import requests

def send_outlook(token, to, subject, body):
    requests.post(
        'https://graph.microsoft.com/v1.0/me/sendMail',
        headers={'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'},
        json={'message': {
            'subject': subject,
            'body': {'contentType': 'HTML', 'content': body},
            'toRecipients': [{'emailAddress': {'address': to}}]
        }}
    )

Method 4 — Async (aiosmtplib)

import asyncio, aiosmtplib
from email.message import EmailMessage

async def send_async(to, subject, body):
    msg = EmailMessage()
    msg['From'] = 'you@gmail.com'
    msg['To'] = to
    msg['Subject'] = subject
    msg.set_content(body)
    await aiosmtplib.send(msg, hostname='smtp.gmail.com', port=465, use_tls=True,
                          username='you@gmail.com', password='APP_PASSWORD')

asyncio.run(send_async('them@example.com', 'Hello', 'World'))

Choosing

  • Testing / low volume: SMTP + Gmail
  • Production / high volume: SendGrid or Mailgun API
  • Outlook/Microsoft 365: Microsoft Graph API
  • High concurrency: aiosmtplib
For full-featured email automation, see ZeroPhantom's AI Mailer →
ZeroPhantom Support AI-Powered · Usually replies instantly
👋 Hi there! Let's chat.
Fill in your details to get started.
ZeroPhantom Support