Search code examples
pythonwebflaskprojectflask-mail

What does _external=True mean in flask_mail?


import os
import secrets
from PIL import Image
from flask import url_for, current_app
from flask_mail import Message
from app import mail


def save_picture(form_picture):
    random_hex = secrets.token_hex(8)
    f_name, f_ext = os.path.splitext(form_picture.filename)
    picture_fn = random_hex + f_ext
    picture_path = os.path.join(current_app.root_path, 'static/profile_pics', picture_fn)
    output_size = (125, 125)
    i = Image.open(form_picture)
    i.thumbnail(output_size)
    i.save(picture_path)
    return picture_fn

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message('Password Reset Request', sender='[email protected]', recipients=[user.email])
    msg.body = f''' To reset your password, visit the following link:
{url_for('users.reset_token', token=token, **_external=True**)}
If you did not make this request then simply ignore this email and no changes will be made
    '''
    mail.send(msg)

I'm making a Flask app and learning how to send reset emails with flask_mail module so i am wondering what does _external=True(send_reset_email function) mean when i put the reset link on a message body. I've searched on Google but i haven't found anything. Thank you in advance.


Solution

  • _external=True tells Flask that it should generate an absolute URL, and not a relative URL. For example, https://example.com/my-page is an absolute URL, but /my-page is a relative URL. Since you're sending an email, a relative URL to a page in your site won't work.

    You can see the documentation for url_for here: https://flask.palletsprojects.com/en/1.1.x/api/#flask.url_for

    _external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which falls back to the Host header, then to the IP and port of the request.