Send HTML emails with Flask-Mail using SMTP and Jinja2 email templates.
Sending Email with Flask-Mail
pip install flask-mail
from flask_mail import Mail, Message
mail = Mail()
app.config.update(
MAIL_SERVER = "smtp.gmail.com",
MAIL_PORT = 587,
MAIL_USE_TLS = True,
MAIL_USERNAME = os.environ["MAIL_USERNAME"],
MAIL_PASSWORD = os.environ["MAIL_PASSWORD"],
)
mail.init_app(app)
def send_welcome_email(user):
msg = Message(
subject = "Welcome!",
sender = "noreply@myapp.com",
recipients = [user.email],
)
msg.body = "Hi " + user.name + ", welcome to MyApp!"
msg.html = render_template("emails/welcome.html", user=user)
mail.send(msg)
# Async with threading
from threading import Thread
def send_async(app, msg):
with app.app_context():
mail.send(msg)
Thread(target=send_async, args=(app, msg)).start()