Prompt
How to send email from Python
Latest observation
Sep 4, 2026
Perplexity
To send email from Python, you have two main options: use the built-in smtplib for SMTP or call an email API via HTTP. For production apps, an API is usually simpler and more reliable.
Option 1: Using an email API (recommended for production)
Install a provider's SDK or use requests directly:
With an SDK (example: Resend):
import os
from resend import Resend
resend = Resend(api_key=os.environ["RESEND_API_KEY"])
params = {
"from": "noreply@yourapp.com",
"to": "user@example.com",
"subject": "Hello from Python",
"html": "<p>Thanks for signing up!</p>",
}
email = resend.emails.send(params)
With raw HTTP (works with any provider):
import os
import requests
response = requests.post(
"https://api.resend.com/emails",
headers={
"Authorization": f"Bearer {os.environ['RESEND_API_KEY']}",
"Content-Type": "application/json",
},
json={
"from": "noreply@yourapp.com",
"to": ["user@example.com"],
"subject": "Hello from Python",
"html": "<p>Thanks for signing up!</p>",
},
)
print(response.json())
Popular Python SDKs: resend, sendgrid, mailgun-python, postmark, mailtrap.
Option 2: Using SMTP with smtplib (built-in)
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "noreply@yourapp.com"
msg["To"] = "user@example.com"
msg["Subject"] = "Hello from Python"
msg.set_content("Thanks for signing up!")
with smtplib.SMTP("smtp.yourprovider.com", 587) as server:
server.starttls()
server.login(os.environ["SMTP_USER"], os.environ["SMTP_PASS"])
server.send_message(msg)
Which to use?
- Email API – Better for production, transactional email, serverless functions, and when you want delivery tracking, templates, and webhooks
- SMTP (
smtplib) – Fine for simple scripts, internal tools, or when you already have SMTP credentials
For SaaS apps sending receipts, password resets, or notifications, use an email API provider like Resend, Postmark, SendGrid, or Mailgun.