Skip to content

Send Email with Python

  1. Sign up for an email delivery service and generate an API key
  2. Verify your sending domain with SPF and DKIM records
  3. Choose your sending method — REST API (requests) or SMTP (smtplib)
  4. Build the email payload with sender, recipient, subject, and HTML body
  5. Send the email and handle the response
  6. Set up webhooks to track delivery, bounces, and opens
import requests
import os
response = requests.post(
"https://api.relaypost.dev/v1/emails/send",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ['RELAYPOST_API_KEY']}",
},
json={
"from": {"email": "[email protected]", "name": "Your App"},
"to": [{"email": "[email protected]"}],
"subject": "Your order has shipped",
"html": "<h1>Order Shipped</h1><p>Your package is on the way.</p>",
},
)
result = response.json()
print(result["data"]["message_id"])

Python’s built-in smtplib works with any SMTP relay. No dependencies required.

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

msg = MIMEMultipart(“alternative”) msg[“Subject”] = “Your order has shipped” msg[“From”] = “[email protected]” msg[“To”] = “[email protected]

html = “

Order Shipped

Your package is on the way.

” msg.attach(MIMEText(html, “html”))

with smtplib.SMTP(“smtp.relaypost.dev”, 587) as server: server.starttls() server.login(os.environ[“SMTP_USERNAME”], os.environ[“SMTP_PASSWORD”]) server.sendmail(msg[“From”], [msg[“To”]], msg.as_string())

## Error Handling
```python
import requests
import os
try:
response = requests.post(
"https://api.relaypost.dev/v1/emails/send",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ['RELAYPOST_API_KEY']}",
},
json={
"from": {"email": "[email protected]"},
"to": [{"email": "[email protected]"}],
"subject": "Hello",
"html": "<p>Hello from RelayPost</p>",
},
)
response.raise_for_status()
result = response.json()
print(result["data"]["message_id"])
except requests.exceptions.HTTPError as e:
error = e.response.json()
print(f"Send failed: {error['error']['code']} - {error['error']['message']}")
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")

What is the easiest way to send email with Python?

Section titled “What is the easiest way to send email with Python?”

The easiest way is using the requests library with a REST email API. A single POST request with your API key and JSON payload sends the email. No SMTP configuration or email-specific libraries required.

Use the REST API with requests for new projects — it is simpler and gives you access to advanced features. Use smtplib if your existing codebase already uses SMTP or if you want to avoid external dependencies.

Django has built-in SMTP support. Set EMAIL_HOST = "smtp.relaypost.dev", EMAIL_PORT = 587, and configure your SMTP credentials in settings.py. Then use Django’s send_mail() function as usual.