1. Install Flask-Mail
pip install Flask-Mail
2. Configure SMTP
import os
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.update(
MAIL_SERVER="smtp.sendcorex.com",
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME=os.environ["SENDCOREX_API_KEY"],
MAIL_PASSWORD=os.environ["SENDCOREX_API_KEY"],
MAIL_DEFAULT_SENDER=("Acme", "hello@yourdomain.com"),
)
mail = Mail(app)
3. Send an email
@app.post("/signup")
def signup():
msg = Message("Welcome to Acme", recipients=["user@example.com"])
msg.body = "Thanks for signing up!"
msg.html = "<html><body><p>Thanks for signing up!</p></body></html>"
mail.send(msg)
return {"ok": True}
For anything slower than a quick signup email, send from a background job (RQ, Celery) so the request doesn't wait on SMTP.
Without Flask-Mail: plain smtplib
import smtplib, os
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Acme <hello@yourdomain.com>"
msg["To"] = "user@example.com"
msg["Subject"] = "Welcome to Acme"
msg.set_content("Thanks for signing up!")
with smtplib.SMTP("smtp.sendcorex.com", 587) as s:
s.starttls()
key = os.environ["SENDCOREX_API_KEY"]
s.login(key, key)
s.send_message(msg)
Authenticate your domain
Publish SPF, DKIM and DMARC for the sending domain before going live, and keep one sender name that matches your brand. Check the result with our SPF, DKIM and DMARC checker.