Flask – Email with images

This tutorial show how to send email with images render properly.

Library Required

(venv) $ pip install flask-mail


    # Email
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USE_SSL'] = True
    app.config['MAIL_DEFAULT_SENDER'] = ('In-house','xxx.noreply@gmail.com')
    app.config['MAIL_MAX_EMAILS'] = 10
    app.config['MAIL_USERNAME'] = 'xxx.noreply@gmail.com'
    app.config['MAIL_PASSWORD'] = 'xxx'
    app.config['MAIL_SUBJECT_PREFIX'] = 'XXX '


from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from . import mail
from .decorators import async

def send_async_email(app, msg):
    with app.app_context():

def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    send_async_email(app, msg)


from threading import Thread

def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
    return wrapper


def index():
    subject = "[Announcement] #{} - {}".format('Software update','(minor)')
    receiver = "XXX@gmail.com"
    send_email(receiver, subject, 'mail/release')
    return render_template('mail/release.html')



      <img src="{{ url_for('static', filename='products.jpg', _external=True) }}" />


Gmail Setup

Turn on setting in https://myaccount.google.com/lesssecureapps

Testing Images

If you only run on localhost, you’ll not get the desire result when you received the email. This is due to the images are not able to read from the mail server. One of the solution is to use 3th party tools like ngork┬áto secure tunnels back to localhost.

Start Ngork

./ngrok http 5000


Flask – Email with images

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.