Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send html email using flask in Python

I want to send HTML webpage as a mail body using Python and Flask. I tried using MIME module, but somehow I am not being able to send mail. If anyone has any expertise on this, can you please help me.

It would be great if you could provide some code as well.

like image 480
user1862226 Avatar asked Feb 09 '17 12:02

user1862226


1 Answers

flask-mail is a good tool that I use to render the template to render HTML as the body of my mail.

from flask_mail import Message
from flask import render_template
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    
def send_mail_flask(to,subject,template,**kwargs):
    msg = Message(subject=subject,sender='[email protected]', recipients=to)
    msg.body = render_template('template.txt', **kwargs)
    msg.html = render_template('template.html', **kwargs)
    mail.send(msg)

The template is the HTML file you wish to include in your mail and you can also add a text version using msg.body!

You may need to add more environment variables according to the SMTP service you use.

like image 200
Espoir Murhabazi Avatar answered Sep 28 '22 19:09

Espoir Murhabazi