Sending emails in Flask

Privalov Vladimir
2 min readMay 1, 2021

When working on Flask project we often need a functionality to send emails to users. For instance, when registering user we would like to verify his email address or if a user forgot his password and we need to allow him to reset password.

There is a library Flask-Mail which comes very handy when we need to send emails and requires no complicated setup.

Install it:

pip install flask-mail

First wee need to create a config for email sender:

app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'support@yourcompany.com' # enter your email here
app.config['MAIL_DEFAULT_SENDER'] = 'support@yourcompany.com' # enter your email here
app.config['MAIL_PASSWORD'] = 'password' # enter your password here

Then we create an instance of class Mail in app/__init__.py:

from flask_mail import Mailapp = Flask(__name__)
...
mail = Mail(app)

We can easily test sending emails in Flask shell. Run command in the app root

flask shell

Then write in terminal:

>>> from app import mail
>>> from flask_mail import Message
>>>
>>> msg = Message("Subject", recipients=["<your email address>"])
msg.html = "<h2>Email Heading</h2>\n<p>Email Body</p>"
>>>
>>> mail.send(msg)
>>>

Here we simply import library and create an object of type Message. Constructor for Message takes two arguments: email subject and a list of recipients.

We then specify email message using attribute html on the object msg and finally send email calling method send() on object mail.

Let’s first create a config for different types of email messages:

EMAIL_CONFIG = {
'email_address_verification': {
'from': '',
'subject': 'Verify your email for %s' % app.config['APP_TITLE'],
'html_template': 'mail/email_verification.html'
},
'password_reset': {
'from': '',
'subject': 'Reset your password for %s' % app.config['APP_TITLE'],
'html_template': 'mail/password_reset.html'
}
]

In Flask we can create a special class EmailSender for sending emails

class EmailSender:
def __init__(self, email: str, email_type: str):
self.email = email
self.config = EMAIL_CONFIG[email_type]

Specify method send:

def send(self, data: dict) -> None:
if not EmailSender.isConfigured():
raise CustomError({'message': 'Error when sending email: Email provider is not configured. Please configure it in config.py\n'})
msg = Message(self.config['subject'], sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[self.email])
msg.html = render_template(self.config['html_template'], **data)
mail.send(msg)

and method isConfigured

def isConfigured() -> bool:
return (not app.config['MAIL_DEFAULT_SENDER'] is None and not app.config['MAIL_SERVER'] is None)

which verifies whether the email sending config is set up.

Let’s create a test method for using EmailSender class

email_sender = EmailSender(email, 'email_address_verification')
data = {
'link': link,
'title': app.config['APP_TITLE']
}
email_sender.send(data)

We can create html templates for mails

<p>Hello,</p>
<p>Please verify your email address.</p>
<p><a href="{{ link }}">click here</p>
<p>If you didn’t ask to verify this address, you can ignore this email.</p>
<p>Thanks,</p>
<p>Your {{ app_title }} team</p>

That’s it. Good luck with developing web applications using Flask.

--

--