Flask – Email with images

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

Library Required

(venv) $ pip install flask-mail

Config

    # 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 '

Email.py

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

@async
def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

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

Decorators.py

from threading import Thread

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

View.py

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

 

Release.html

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

 

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.