P H O T O N

CONSOLE

Loading

Python 3 Developer Guide

How to Send Email Using Python SMTP Relay
Production smtplib • STARTTLS Encryption • Retry Logic

Send transactional emails in Python with zero external libraries. Complete code snippets for HTML emails, attachments, and automatic retry queues.

5 min read • Python 3.8+ Compatible • Copy-Paste Ready
Direct Answer: Sending Email with Python smtplib

In Python, send email by initializing smtplib.SMTP(host, 587), creating an SSL/TLS security context with server.starttls(), authenticating with server.login(username, password), and dispatching an EmailMessage or MIMEMultipart object via server.send_message(msg). For high-volume production, manage secrets via python-dotenv and implement retry backoff loops for connection exceptions.

1. Python smtplib vs. REST API: When to Use Which

Python developers typically choose between standard SMTP and HTTP REST APIs:

  • Use smtplib: When building Django, Flask, or Celery apps where standard SMTP drivers are natively supported without third-party dependencies.
  • Use REST API: In AWS Lambda or Google Cloud Run microservices where persistent TCP sockets are impractical.

2. Complete Python Code Snippet (HTML + Plaintext)

import smtplib
import ssl
from email.message import EmailMessage

# 1. Define Message Parameters
msg = EmailMessage()
msg['Subject'] = "Your One-Time Verification Code"
msg['From'] = "Security Team <auth@yourdomain.com>"
msg['To'] = "recipient@example.com"

# Plaintext fallback
msg.set_content("Your login OTP is: 849201. It expires in 5 minutes.")

# HTML Rich Body
msg.add_alternative("""
<div style="font-family: sans-serif; padding: 20px;">
  <h2>Your Login Verification Code</h2>
  <p style="font-size: 24px; font-weight: bold; color: #4F46E5;">849201</p>
  <p style="color: #64748B;">Expires in 5 minutes.</p>
</div>
""", subtype='html')

# 2. Connect & Dispatch via PhotonRelay
context = ssl.create_default_context()
with smtplib.SMTP("mail.photonrelay.com", 587) as server:
    server.starttls(context=context)
    server.login("your_photon_api_key", "your_photon_api_secret")
    server.send_message(msg)
    print("Email dispatched successfully!")

3. Adding Attachments with email.mime

To attach PDF invoices or receipts, read the file in binary mode:

with open('invoice_1092.pdf', 'rb') as f:
    file_data = f.read()
    file_name = f.name

msg.add_attachment(file_data, maintype='application', subtype='pdf', filename=file_name)

4. Handling Network Timeouts & Retry Backoff

import time

def send_with_retry(msg, max_retries=3):
    for attempt in range(max_retries):
        try:
            with smtplib.SMTP("mail.photonrelay.com", 587, timeout=10) as s:
                s.starttls()
                s.login("key", "secret")
                s.send_message(msg)
                return True
        except (smtplib.SMTPServerDisconnected, TimeoutError) as e:
            wait = 2 ** attempt
            print(f"Error: {e}. Retrying in {wait}s...")
            time.sleep(wait)
    return False

Send Sub-Second Emails in Python with PhotonRelay

Deploy in minutes. Get 5,000 free monthly transactional emails and transparent $0.50/1k pay-as-you-go scaling.

6. Frequently Asked Questions

Use smtplib.SMTP() with server.starttls() on port 587. It offers the broadest network compatibility across modern cloud hosts (AWS, GCP, DigitalOcean) and negotiates TLS 1.3 securely.

Wrap the socket dispatch in a try/except block catching (smtplib.SMTPServerDisconnected, smtplib.SMTPConnectError, TimeoutError), and implement exponential backoff retry logic (e.g., retrying after 2s, 4s, 8s).

Yes. Photon Console provides a lightweight REST API endpoint that can be invoked via python 'requests' or 'httpx', providing sub-150ms HTTP injection.