user1862226
user1862226

Reputation: 157

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.

Upvotes: 14

Views: 27432

Answers (5)

Chukwunazaekpere
Chukwunazaekpere

Reputation: 1012

Firstly, ensure there's a folder in your apps directory called templates. This is where all your html templates should be.

**server.py**


from flask-mail import Mail, Message
from flask import Flask

import os

app = Flask(__name__)
send_mail = Mail(app)

 context={
   "fullname": fullname,
   "otp_code": otp_code,
   "year": datetime.now().year,
   "subject":"Registration Mail",
}
email_message = Message(
   subject=mail_subject,
   sender=os.getenv("ADMIN_EMAIL"),
   recipients=[receipients_email],
   html=render_template(template_name_or_list="otp.html", **context)
)
send_mail.send(email_message)

where "otp.html" is an existing html template in your templates folder

Upvotes: 0

miksus
miksus

Reputation: 3417

I recently made a pretty awesome email library and I decided to make a Flask extension for it as well: Flask-Redmail

Install

pip install flask-redmail

Configuration

from flask import Flask
from flask_redmail import RedMail

app = Flask(__name__)
email = RedMail(app)

# Setting configs
app.config["EMAIL_HOST"] = "localhost"
app.config["EMAIL_PORT"] = 0

app.config["EMAIL_USERNAME"] = "[email protected]"
app.config["EMAIL_PASSWORD"] = "<PASSWORD>"

app.config["EMAIL_SENDER"] = "[email protected]"

Simple Example

You may send emails simply:

@app.route("/send-email")
def send_email():
    email.send(
        subject="Example email",
        receivers=["[email protected]"],
        html="""
            <h1>Hi,</h1>
            <p>this is an example.</p>
        """
    )

Template Example

It can also use your default Jinja env. Create a file emails/verify.html to your Flask template folder that looks like this:

<h1>Hi, you visited {{ request.endpoint }}.</h1>

Then use this template:

@app.route("/send-email-template")
def send_email():
    email.send(
        subject="Template example",
        receivers=["[email protected]"],
        html_template="emails/verify.html"
    )

Flask Redmail is quite a simple wrapper for Red Mail and Red Mail is pretty extensive. It can:

  • Send attachments from various types
  • Embed images and plots to the HTML
  • Embed prettified tables to the HTML
  • Supports Jinja out-of-the-box
  • Gmail and Outlook are preconfigured

I hope you find it useful.

Links:

Red Mail:

Upvotes: 6

Espoir Murhabazi
Espoir Murhabazi

Reputation: 6376

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.

Upvotes: 22

izudada
izudada

Reputation: 1

On a separate python file (emails.py) I created an email class that contains all the emails (as class methods) to be sent to the user based on his actions as below:

class Email:

    def accountCreation():
        body = "<html> <body> <p> {} </p> <br> <br>  <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </body> </html>"
        return body

then on another file (app.py) where I made use of flask_mail library I have:

from flask_mail import Mail, Message
import emails

mailer = emails.Email()

try:
    email = "[email protected]"
    body = mailer.accountCreation()
    msg = Message('Hello',recipients=[email])
                                
    msg.html =  body 
    mail.send(msg)
except Exception as e:
    print(e)

Upvotes: 0

Igor
Igor

Reputation: 2909

Try using FlaskMail https://pythonhosted.org/flask-mail/

msg = Message(
    recipients=[''],
    sender='[email protected]',
    reply_to='[email protected]',
    subject=mail.subject
  )
msg.html = mail.body
mail.send(msg)

here, mail is an imported file from "mails" directory, and body is an HTML markup.

Upvotes: 2

Related Questions