The Flask Mega-Tutorial Part X: Email Support

This is the tenth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how your application can send emails to your users, and how to build a password recovery feature on top of the email support.

For your reference, below is a list of the articles in this series.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

The application is doing pretty well on the database front now, so in this chapter I want to depart from that topic and add another important piece that most web applications need, which is the sending of emails.

Why does an application need to email its users? There are many reasons, but one common one is to solve authentication related problems. In this chapter I'm going to add a password reset feature for users that forget their password. When a user requests a password reset, the application will send an email with a specially crafted link. The user then needs to click that link to have access to a form in which to set a new password.

The GitHub links for this chapter are: Browse, Zip, Diff.

Introduction to Flask-Mail

As far as the actual sending of emails, Flask has a popular extension called Flask-Mail that can make the task very easy. As always, this extension is installed with pip:

(venv) $ pip install flask-mail

The password reset links will have a secure token in them. To generate these tokens, I'm going to use JSON Web Tokens, which also have a popular Python package:

(venv) $ pip install pyjwt

The Flask-Mail extension is configured from the app.config object. Remember when in Chapter 7 I added the email configuration for sending yourself an email whenever an error occurred in production? I did not tell you this then, but my choice of configuration variables was modeled after Flask-Mail's requirements, so there isn't really any additional work that is needed, the configuration variables are already in the application.

Like most Flask extensions, you need to create an instance right after the Flask application is created. In this case this is an object of class Mail:

app/__init__.py: Flask-Mail instance.

# ...
from flask_mail import Mail

app = Flask(__name__)
# ...
mail = Mail(app)

If you are planning to test sending of emails you have the same two options I mentioned in Chapter 7. If you want to use an emulated email server, Python provides one that is very handy that you can start in a second terminal with the following command:

(venv) $ python -m smtpd -n -c DebuggingServer localhost:8025

To configure for this server you will need to set two environment variables:

(venv) $ export MAIL_SERVER=localhost
(venv) $ export MAIL_PORT=8025

If you prefer to have emails sent for real, you need to use a real email server. If you have one, then you just need to set the MAIL_SERVER, MAIL_PORT, MAIL_USE_TLS, MAIL_USERNAME and MAIL_PASSWORD environment variables for it. If you want a quick solution, you can use a Gmail account to send email, with the following settings:

(venv) $ export MAIL_SERVER=smtp.googlemail.com
(venv) $ export MAIL_PORT=587
(venv) $ export MAIL_USE_TLS=1
(venv) $ export MAIL_USERNAME=<your-gmail-username>
(venv) $ export MAIL_PASSWORD=<your-gmail-password>

If you are using Microsoft Windows, you need to replace export with set in each of the export statements above.

Remember that the security features in your Gmail account may prevent the application from sending emails through it unless you explicitly allow "less secure apps" access to your Gmail account. You can read about this here, and if you are concerned about the security of your account, you can create a secondary account that you configure just for testing emails, or you can enable less secure apps only temporarily to run your tests and then revert back to the more secure default.

Flask-Mail Usage

To learn how Flask-Mail works, I'll show you how to send an email from a Python shell. So fire up Python with flask shell, and then run the following commands:

>>> from flask_mail import Message
>>> from app import mail
>>> msg = Message('test subject', sender=app.config['ADMINS'][0],
... recipients=['your-email@example.com'])
>>> msg.body = 'text body'
>>> msg.html = '<h1>HTML body</h1>'
>>> mail.send(msg)

The snippet of code above will send an email to a list of email addresses that you put in the recipients argument. I put the sender as the first configured admin (I've added the ADMINS configuration variable in Chapter 7). The email will have plain text and HTML versions, so depending on how your email client is configured you may see one or the other.

So as you see, this is pretty simple. Now let's integrate emails into the application.

A Simple Email Framework

I will begin by writing a helper function that sends an email, which is basically a generic version of the shell exercise from the previous section. I will put this function in a new module called app/email.py:

app/email.py: Email sending wrapper function.

from flask_mail import Message
from app import mail

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body

Flask-Mail supports some features that I'm not utilizing here such as Cc and Bcc lists. Be sure to check the Flask-Mail Documentation if you are interested in those options.

Requesting a Password Reset

As I mentioned above, I want users to have the option to request their password to be reset. For this purpose I'm going to add a link in the login page:

app/templates/login.html: Password reset link in login form.

        Forgot Your Password?
        <a href="{{ url_for('reset_password_request') }}">Click to Reset It</a>

When the user clicks the link, a new web form will appear that requests the user's email address as a way to initiate the password reset process. Here is the form class:

app/forms.py: Reset password request form.

class ResetPasswordRequestForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email()])
    submit = SubmitField('Request Password Reset')

And here is the corresponding HTML template:

app/templates/reset_password_request.html: Reset password request template.

{% extends "base.html" %}

{% block content %}
    <h1>Reset Password</h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
            {{ form.email.label }}<br>
            {{ form.email(size=64) }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        <p>{{ form.submit() }}</p>
{% endblock %}

I also need a view function to handle this form:

app/routes.py: Reset password request view function.

from app.forms import ResetPasswordRequestForm
from app.email import send_password_reset_email

@app.route('/reset_password_request', methods=['GET', 'POST'])
def reset_password_request():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = ResetPasswordRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
        flash('Check your email for the instructions to reset your password')
        return redirect(url_for('login'))
    return render_template('reset_password_request.html',
                           title='Reset Password', form=form)

This view function is fairly similar to others that process a form. I start by making sure the user is not logged in. If the user is logged in, then there is no point in using the password reset functionality, so I redirect to the index page.

When the form is submitted and valid, I look up the user by the email provided by the user in the form. If I find the user, I send a password reset email. I'm using a send_password_reset_email() helper function to do this. I will show you this function below.

After the email is sent, I flash a message directing the user to look for the email for further instructions, and then redirect back to the login page. You may notice that the flashed message is displayed even if the email provided by the user is unknown. This is so that clients cannot use this form to figure out if a given user is a member or not.

Password Reset Tokens

Before I implement the send_password_reset_email() function, I need to have a way to generate a password request link. This is going to be the link that is sent to the user via email. When the link is clicked, a page where a new password can be set is presented to the user. The tricky part of this plan is to make sure that only valid reset links can be used to reset an account's password.

The links are going to be provisioned with a token, and this token will be validated before allowing the password change, as proof that the user that requested the email has access to the email address on the account. A very popular token standard for this type of process is the JSON Web Token, or JWT. The nice thing about JWTs is that they are self contained. You can send a token to a user in an email, and when the user clicks the link that feeds the token back into the application, it can be verified on its own.

How do JWTs work? Nothing better than a quick Python shell session to understand them:

>>> import jwt
>>> token = jwt.encode({'a': 'b'}, 'my-secret', algorithm='HS256')
>>> token
>>> jwt.decode(token, 'my-secret', algorithms=['HS256'])
{'a': 'b'}

The {'a': 'b'} dictionary is an example payload that is going to be written into the token. To make the token secure, a secret key needs to be provided to be used in creating a cryptographic signature. For this example I have used the string 'my-secret', but with the application I'm going to use the SECRET_KEY from the configuration. The algorithm argument specifies how the token is to be generated. The HS256 algorithm is the most widely used.

As you can see the resulting token is a long sequence of characters. But do not think that this is an encrypted token. The contents of the token, including the payload, can be decoded easily by anyone (don't believe me? Copy the above token and then enter it in the JWT debugger to see its contents). What makes the token secure is that the payload is signed. If somebody tried to forge or tamper with the payload in a token, then the signature would be invalidated, and to generate a new signature the secret key is needed. When a token is verified, the contents of the payload are decoded and returned back to the caller. If the token's signature was validated, then the payload can be trusted as authentic.

The payload that I'm going to use for the password reset tokens is going to have the format {'reset_password': user_id, 'exp': token_expiration}. The exp field is standard for JWTs and if present it indicates an expiration time for the token. If a token has a valid signature, but it is past its expiration timestamp, then it will also be considered invalid. For the password reset feature, I'm going to give these tokens 10 minutes of life.

When the user clicks on the emailed link, the token is going to be sent back to the application as part of the URL, and the first thing the view function that handles this URL will do is to verify it. If the signature is valid, then the user can be identified by the ID stored in the payload. Once the user's identity is known, the application can ask for a new password and set it on the user's account.

Since these tokens belong to users, I'm going to write the token generation and verification functions as methods in the User model:

app/models.py: Reset password token methods.

from time import time
import jwt
from app import app

class User(UserMixin, db.Model):
    # ...

    def get_reset_password_token(self, expires_in=600):
        return jwt.encode(
            {'reset_password': self.id, 'exp': time() + expires_in},
            app.config['SECRET_KEY'], algorithm='HS256')

    def verify_reset_password_token(token):
            id = jwt.decode(token, app.config['SECRET_KEY'],
        return User.query.get(id)

The get_reset_password_token() function returns a JWT token as a string, which is generated directly by the jwt.encode() function.

The verify_reset_password_token() is a static method, which means that it can be invoked directly from the class. A static method is similar to a class method, with the only difference that static methods do not receive the class as a first argument. This method takes a token and attempts to decode it by invoking PyJWT's jwt.decode() function. If the token cannot be validated or is expired, an exception will be raised, and in that case I catch it to prevent the error, and then return None to the caller. If the token is valid, then the value of the reset_password key from the token's payload is the ID of the user, so I can load the user and return it.

Sending a Password Reset Email

Now that I have the tokens, I can generate the password reset emails. The send_password_reset_email() function relies on the send_email() function I wrote above.

app/email.py: Send password reset email function.

from flask import render_template
from app import app

# ...

def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email('[Microblog] Reset Your Password',
                                         user=user, token=token),
                                         user=user, token=token))

The interesting part in this function is that the text and HTML content for the emails is generated from templates using the familiar render_template() function. The templates receive the user and the token as arguments, so that a personalized email message can be generated. Here is the text template for the reset password email:

app/templates/email/reset_password.txt: Text for password reset email.

Dear {{ user.username }},

To reset your password click on the following link:

{{ url_for('reset_password', token=token, _external=True) }}

If you have not requested a password reset simply ignore this message.


The Microblog Team

And here is the nicer HTML version of the same email:

app/templates/email/reset_password.html: HTML for password reset email.

<p>Dear {{ user.username }},</p>
    To reset your password
    <a href="{{ url_for('reset_password', token=token, _external=True) }}">
        click here
<p>Alternatively, you can paste the following link in your browser's address bar:</p>
<p>{{ url_for('reset_password', token=token, _external=True) }}</p>
<p>If you have not requested a password reset simply ignore this message.</p>
<p>The Microblog Team</p>

The reset_password route that is referenced in the url_for() call in these two email templates does not exist yet, this will be added in the next section. The _external=True argument that I included in the url_for() calls in both templates is also new. The URLs that are generated by url_for() by default are relative URLs, so for example, the url_for('user', username='susan') call would return /user/susan. This is normally sufficient for links that are generated in web pages, because the web browser takes the remaining parts of the URL from the current page. When sending a URL by email however, that context does not exist, so fully qualified URLs need to be used. When _external=True is passed as an argument, complete URLs are generated, so the previous example would return http://localhost:5000/user/susan, or the appropriate URL when the application is deployed on a domain name.

Resetting a User Password

When the user clicks on the email link, a second route associated with this feature is triggered. Here is the password request view function:

app/routes.py: Password reset view function.

from app.forms import ResetPasswordForm

@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    user = User.verify_reset_password_token(token)
    if not user:
        return redirect(url_for('index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        flash('Your password has been reset.')
        return redirect(url_for('login'))
    return render_template('reset_password.html', form=form)

In this view function I first make sure the user is not logged in, and then I determine who the user is by invoking the token verification method in the User class. This method returns the user if the token is valid, or None if not. If the token is invalid I redirect to the home page.

If the token is valid, then I present the user with a second form, in which the new password is requested. This form is processed in a way similar to previous forms, and as a result of a valid form submission, I invoke the set_password() method of User to change the password, and then redirect to the login page, where the user can now login.

Here is the ResetPasswordForm class:

app/forms.py: Password reset form.

class ResetPasswordForm(FlaskForm):
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Request Password Reset')

And here is the corresponding HTML template:

app/templates/reset_password.html: Password reset form template.

{% extends "base.html" %}

{% block content %}
    <h1>Reset Your Password</h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.password2.label }}<br>
            {{ form.password2(size=32) }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        <p>{{ form.submit() }}</p>
{% endblock %}

The password reset feature is now complete, so make sure you try it.

Asynchronous Emails

If you are using the simulated email server that Python provides you may not have noticed this, but sending an email slows the application down considerably. All the interactions that need to happen when sending an email make the task slow, it usually takes a few seconds to get an email out, and maybe more if the email server of the addressee is slow, or if there are multiple addressees.

What I really want is for the send_email() function to be asynchronous. What does that mean? It means that when this function is called, the task of sending the email is scheduled to happen in the background, freeing the send_email() to return immediately so that the application can continue running concurrently with the email being sent.

Python has support for running asynchronous tasks, actually in more than one way. The threading and multiprocessing modules can both do this. Starting a background thread for email being sent is much less resource intensive than starting a brand new process, so I'm going to go with that approach:

app/email.py: Send emails asynchronously.

from threading import Thread
# ...

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

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email, args=(app, msg)).start()

The send_async_email function now runs in a background thread, invoked via the Thread() class in the last line of send_email(). With this change, the sending of the email will run in the thread, and when the process completes the thread will end and clean itself up. If you have configured a real email server, you will definitely notice a speed improvement when you press the submit button on the password reset request form.

You probably expected that only the msg argument would be sent to the thread, but as you can see in the code, I'm also sending the application instance. When working with threads there is an important design aspect of Flask that needs to be kept in mind. Flask uses contexts to avoid having to pass arguments across functions. I'm not going to go into a lot of detail on this, but know that there are two types of contexts, the application context and the request context. In most cases, these contexts are automatically managed by the framework, but when the application starts custom threads, contexts for those threads may need to be manually created.

There are many extensions that require an application context to be in place to work, because that allows them to find the Flask application instance without it being passed as an argument. The reason many extensions need to know the application instance is because they have their configuration stored in the app.config object. This is exactly the situation with Flask-Mail. The mail.send() method needs to access the configuration values for the email server, and that can only be done by knowing what the application is. The application context that is created with the with app.app_context() call makes the application instance accessible via the current_app variable from Flask.


  • #176 Miguel Grinberg said 2020-01-08T17:26:08Z

    @Hassan: all the browser tabs share the same cookie repository, you cannot have two tabs with different logged in users. Try using two different web browsers, or a private and a normal window of a single browser.

  • #177 Marek said 2020-01-23T06:45:34Z

    Hi, I have a strange issue with async email sending. It seems that mail.send(msg) call hangs until I restart the app service.

    Here's the code: def send_async_email(app, msg): app.logger.info('send_async_email:before_context') with app.app_context(): app.logger.info('send_async_email:in_context:before_email') mail.send(msg) app.logger.info('send_async_email:in_context:after_email')

    def send_email(subject:str, text_body:Optional[str]=None, html_body:Optional[str]=None) -> None: msg = Message(subject, sender=current_app.config['SENDER'], recipients=[current_app.config['RECEIVER']]) msg.body = text_body msg.html = html_body Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()

    Here are the app logs - you can see the 36s jump in timestamp from before to after sending email - that's how long I waited to restart the service: 2020-01-23 07:34:07,299 INFO: send_async_email:before_context [in ./app/newsletter/email_utils.py:8] 2020-01-23 07:34:07,347 INFO: send_async_email:in_context:before_email [in ./app/newsletter/email_utils.py:10] 2020-01-23 07:34:43,897 INFO: send_async_email:in_context:after_email [in ./app/newsletter/email_utils.py:12] 2020-01-23 07:34:45,172 INFO: service startup [in ./app/init.py:41]

    Here are the postfix logs - you can see the same timestamp jump between the first and the second lines: Jan 23 07:34:07 x0z13 postfix/smtpd[28080]: connect from localhost[::1] Jan 23 07:34:43 x0z13 postfix/smtpd[28080]: C7A52BD000F0: client=localhost[::1] Jan 23 07:34:43 x0z13 postfix/cleanup[28227]: C7A52BD000F0: message-id=157976124729.27920.14517572585706496476@CENSORED Jan 23 07:34:43 x0z13 postfix/qmgr[2970]: C7A52BD000F0: from=logger@x0z13.com, size=529, nrcpt=1 (queue active) Jan 23 07:34:43 x0z13 postfix/smtpd[28080]: disconnect from localhost[::1] ehlo=1 mail=1 rcpt=1 data=1 quit=1 commands=5 Jan 23 07:34:46 x0z13 postfix/smtp[28228]: C7A52BD000F0: to=CENSORED@protonmail.ch, relay=mail.protonmail.ch[]:25, delay=2.9, delays=0.13/0.07/1.5/1.1, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 8CC41401007D) Jan 23 07:34:46 x0z13 postfix/qmgr[2970]: C7A52BD000F0: removed

    The email is received, but it seems that I need to restart the service for the sending to get unstuck and finalise the transaction.

    Any ideas what is going on?

    BR, Marek

  • #178 Marek said 2020-01-23T16:45:00Z

    The issue was resolved by adding enable_threads = True in the project's ini file. It turns out that without it uwsgi will stop all threads when a handling of a request ends (vide https://github.com/unbit/uwsgi/issues/1141)

  • #179 Jhon said 2020-02-15T06:32:51Z

    Hi Thanks by the Mega-tutorial

    I have a problem at try send email:

    flask smtplib.SMTPServerDisconnected: please run connect() first site:stackoverflow.com

    In localhost work very fine, but in producction never...

    any sugestions Thanks

  • #180 Miguel Grinberg said 2020-02-15T07:56:19Z

    @Jhon: there is no difference between a development or production servers in terms of sending email. Your email settings must be wrong in your server, or your production email server needs a different configuration than the one you are using.

  • #181 Roman said 2020-02-20T09:40:32Z

    Hi Miguel!

    First of all thanks for the tutorial.

    I have a trouble with getting the ResetPasswordForm form. When I click the generated link, that I receive by email, I'm just redirected to login page all the time. Here how it logs it: " - - [20/Feb/2020 11:37:28] "?[32mGET /reset_password/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZXNldCBwYXNzd29yZCI6OSwiZXhwIjoxNTgyMTkyMDM3LjIxMDQzMTh9.nNQSPKt1PLqre1AeLIHI9wmSwkBn4JGwuXFMEIKouaI HTTP/1.1?[0m" 302 - - - [20/Feb/2020 11:37:28] "?[32mGET /index HTTP/1.1?[0m" 302 - - - [20/Feb/2020 11:37:28] "?[37mGET /login?next=%2Findex HTTP/1.1?[0m" 200 - " I've tried to even copy-paste all the changes done in this chapter, but that didn't help anyway. Maybe you could help with it? Thanks.

  • #182 Miguel Grinberg said 2020-02-20T18:34:26Z

    @Roman: you will need to debug this. Add print statements in the view function that receives the reset password token, so that you can determine where it is breaking. My guess is that for some reason the token isn't validated, but I'm not sure why.

  • #183 Aliaksei said 2020-02-25T16:38:49Z

    Hi Miguel! Quote: Regarding (a), the email module in microblog is inside the app package, so it does not collide with the email package from the Python standard library. It's reproducible on windows platform in case of:

    Directory Structure: pack/init.py pack/email.py pack/test_module.py

    Content of init.py:

    import email

    Content of test_module.py

    import email from http import server

    I got an exception: Traceback (most recent call last): File "pack/module_test.py", line 5, in from http import server File "python3/Lib/http/server.py", line 92, in import email.utils ModuleNotFoundError: No module named 'email.utils'; 'email' is not a package

    The case shows server.py imports email.utils, but it is placed at system packages. In case of Flask tutorial application uses werkzeug version = "1.0.0" and werkzeug package includes BaseHHTPRequestHandler with email module.

    Best regards!

  • #184 Miguel Grinberg said 2020-02-25T22:20:15Z

    the python import path in your example includes the directory where email.py is, that's why it fails.

  • #185 Jeffrey Lozano said 2020-03-21T05:00:33Z

    I'm having issues in sending a confirmation email, on the registration process of my flasky app. A SMTPSenderRefused appears on my terminal whenever a registering user tries to send/resend a confirmation email.

    The debugger recommended to follow a link at google support, so I did. I configured my email accordingly as shown: - IMAP: enabled - Access to less secure apps: ON

    And it works! I was able to receive a confirmation email on my gmail account inbox by directly inputting my gmail username and password, on the 2nd argument of MAIL_USERNAME and MAIL_PASSWORD respectively, as shown below:

    config.py MAIL_USERNAME = os.environ.get('MAIL_USERNAME', 'example@gmail.com') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD', 'examplepassword')

    However, I need to integrate this in my application, in order that users can receive a confirmation email during their registration process on the flasky app, so I tried to replace my direct email & password input, with the corresponding attributes from auth/forms.py:

    config.py MAIL_USERNAME = os.environ.get('MAIL_USERNAME', 'email') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD', 'password')

    It did not work! so tried replacing it with:

    config.py MAIL_USERNAME = os.environ.get('MAIL_USERNAME', 'Email') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD', 'Password')

    It still did not work!

    Again, it's already proven to be working with a direct email & password input, wherein I was able to receive an email confirmation from my gmail account, and was also able to successfully confirm my account registration on the flasky app.(As a whole, the code-wise functionality is in good working order!)

    It appears that the narrowed-down root problem is the 2nd argument for both the MAIL_USERNAME and MAIL_PASSWORD; wherein, it seems that a very specific argument needs to be written down.

    What is this specific keyword that I need to write for both my 2nd argument? In accordance to the user input in both the email StringField and PasswordField?

  • #186 Miguel Grinberg said 2020-03-21T23:59:52Z

    @Jeffrey: I don't understand what you are doing. Are you following this tutorial or implementing your own solution? There shouldn't be a second argument on those os.environ.get() calls, that's totally insecure. Set your credentials in the environment variables as indicated in this article.

  • #187 Pratik said 2020-03-30T23:41:07Z

    Any thoughts around using flask-mail vs smtplib? smtplib seems pretty straightforward as well, why to use another wrapper? Thanks

  • #188 Miguel Grinberg said 2020-03-31T09:31:23Z

    @Pratik: I have no thoughts on that. If you like smtplib you should by all means use that. You'll have to implement some sort of configuration pattern on your own though, Flask-Mail does that for you.

  • #189 AR said 2020-04-02T04:40:32Z

    Hi, Is there a way in flask-mail to check whether an email was opened by the recipient or not, and things like which links were clicked within the email body, ?

  • #190 Miguel Grinberg said 2020-04-02T14:13:59Z

    @AR: Not unless you implement it yourself. You may want to consider using a commercial email service if you require that kind of feature, for example SendGrid.

  • #191 sam said 2020-04-05T22:50:35Z

    Awesome tutorial Miguel.

    I have success up until the part of the password reset.

    I had a similar issue to Anthony which I "think" I fixed by declaring

    conn = mail.connect() conn.send(msg)

    in the send_message() function from email.py

    now I am getting this...

    [2020-04-05 15:40:25,093] ERROR in app: Exception on /reset_password_request [POST] Traceback (most recent call last): File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask_compat.py", line 39, in reraise raise value File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\Sam\Documents\lpthw\microblog\app\routes.py", line 154, in reset_password_request send_password_reset_email(user) File "C:\Users\Sam\Documents\lpthw\microblog\app\email.py", line 23, in send_password_reset_email user=user, token=token)) File "C:\Users\Sam\Documents\lpthw\microblog\app\email.py", line 13, in send_email conn.send(msg) File "c:\users\sam\documents\lpthw\microblog\venv\lib\site-packages\flask_mail.py", line 187, in send if self.host: AttributeError: 'Connection' object has no attribute 'host' - - [05/Apr/2020 15:40:25] "?[35m?[1mPOST /reset_password_request HTTP/1.1?[0m" 500 -

    I have tried many different configurations as well

    Thanks in advance for your help

  • #192 Miguel Grinberg said 2020-04-06T22:34:50Z

    @sam: if I understand the Flask-Mail issue, this only happens when the email server drops the connection. So even if you address the crash you will still have an email server that does not want to talk to you. So maybe the solution is to try another email server?

  • #193 Phil said 2020-04-13T08:59:57Z

    Hi Miguel, if you're still updating this, Gmail has changed their service to disallow less secure apps to connect through regular login. Instead, you can generate a 16 character 'app password', which you use in place of your own in the variable. All other steps are the same.

    Great work with this guide!

  • #194 Miguel Grinberg said 2020-04-14T12:54:49Z

    @Phil: both methods are supported as far as I'm aware. You can enable the less secure apps setting or use an app password. If your account has 2-factor authentication enabled, then they only allow app passwords to be used.

  • #195 Daniel said 2020-04-16T18:03:52Z

    Just a comment for those who did not manage to get the email configuration working, having an error like "Username and Password not accepted". You need to tell Gmail to allow access to your account to less secure apps: https://www.google.com/settings/security/lesssecureapps

    @Miguel, thanks a lot for this amazing tutorial, all so crystal clear and complete.

  • #196 sandy said 2020-04-18T19:59:15Z

    Hi Miguel, I'm trying to send an email message as you have explained,but I keep getting this error.What could be the cause of this? I have done everything as you have mentioned. Here is the log of the error message.

    (venv) C:\Users\vinay\microblog>flask shell [2020-04-19 01:13:24,542] INFO in init: Microblog startup Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32 App: app [production] Instance: C:\Users\vinay\microblog\instance

    from flask_mail import Message from app import mail msg = Message('test subject', sender=app.config['ADMINS'][0], ... recipients=['your-email@example.com']) msg.body = 'text body' msg.html = 'HTML body' mail.send(msg) Traceback (most recent call last): File "", line 1, in File "c:\users\vinay\microblog\venv\lib\site-packages\flask_mail.py", line 492, in send message.send(connection) File "c:\users\vinay\microblog\venv\lib\site-packages\flask_mail.py", line 152, in exit self.host.quit() File "c:\python27\lib\smtplib.py", line 772, in quit res = self.docmd("quit") File "c:\python27\lib\smtplib.py", line 393, in docmd self.putcmd(cmd, args) File "c:\python27\lib\smtplib.py", line 341, in putcmd self.send(str) File "c:\python27\lib\smtplib.py", line 333, in send raise SMTPServerDisconnected('please run connect() first') SMTPServerDisconnected: please run connect() first

  • #197 Miguel Grinberg said 2020-04-18T21:56:42Z

    @sandy: my only guess is that your settings are incorrect for your mail server.

  • #198 E_Gr said 2020-04-19T08:00:21Z

    @Anthony Brown For the benefit of anyone reading this now, I had the same problem with the connect() error. Turns out the configuration was indeed the problem. Watch out for spaces when setting environment variables (Windows at least is sensitive to this). set MAIL_SERVER=localhost and not set MAIL_SERVER = localhost

  • #199 E_Gr said 2020-04-19T12:27:28Z

    @Miguel Grinberg Regarding the broad "except" you wrote when decoding the token, wouldn't it be better to use jwt.exceptions.InvalidTokenError? According to their API, this is the base exception of all decode exceptions.


    I was taught that using a broad "except" is bad practice because unintended errors could be swallowed in it and create unexpected behaviors.

  • #200 Miguel Grinberg said 2020-04-19T14:24:05Z

    @E_Gr: using catch-all exception handlers is almost always a bad idea. There is one exception that I consider a valid use though. If you are invoking a third-party function and you want to make sure that regardless of what happens in that call you don't crash, then it is warranted to do a catch-all, in my opinion.

    Imagine the pyjwt library has a bug that causes it to raise a ValueError or similar, so it is not one of the documented exceptions they'll normally raise. I prefer that this type of issue in dependencies, which I have no control, do not make my application crash.

Leave a Comment