0
0
Flaskframework~5 mins

Email verification pattern in Flask

Choose your learning style9 modes available
Introduction

Email verification helps confirm that a user owns the email they provide. It improves security and trust by preventing fake or mistyped emails.

When users sign up and you want to confirm their email address.
When resetting a password to ensure the request is from the real owner.
When sending important notifications that require a verified contact.
When you want to reduce spam or fake accounts in your app.
Syntax
Flask
from flask import Flask, request, redirect, url_for, render_template_string
from itsdangerous import URLSafeTimedSerializer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

def generate_verification_token(email):
    return serializer.dumps(email, salt='email-confirm-salt')

def confirm_verification_token(token, expiration=3600):
    try:
        email = serializer.loads(token, salt='email-confirm-salt', max_age=expiration)
    except Exception:
        return False
    return email

Use URLSafeTimedSerializer to create tokens that expire after some time.

Keep your SECRET_KEY safe and unique for your app.

Examples
This creates a token string for the given email.
Flask
token = generate_verification_token('user@example.com')
print(token)
This checks if the token is valid and not expired, then returns the email.
Flask
email = confirm_verification_token(token)
if email:
    print(f'Email {email} is verified')
else:
    print('Invalid or expired token')
Sample Program

This Flask app lets a user enter their email to register. It creates a verification link with a token. Visiting the link verifies the email if the token is valid and not expired.

Flask
from flask import Flask, request, redirect, url_for, render_template_string
from itsdangerous import URLSafeTimedSerializer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

def generate_verification_token(email):
    return serializer.dumps(email, salt='email-confirm-salt')

def confirm_verification_token(token, expiration=3600):
    try:
        email = serializer.loads(token, salt='email-confirm-salt', max_age=expiration)
    except Exception:
        return False
    return email

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        email = request.form['email']
        token = generate_verification_token(email)
        verify_url = url_for('verify_email', token=token, _external=True)
        return f'Verification link (send by email): {verify_url}'
    return '''<form method="post">
Email: <input name="email" type="email" required>
<input type="submit" value="Register">
</form>'''

@app.route('/verify/<token>')
def verify_email(token):
    email = confirm_verification_token(token)
    if email:
        return f'Email {email} has been verified successfully!'
    else:
        return 'Verification link is invalid or expired.'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

In real apps, send the verification link by email instead of showing it on screen.

Tokens expire after 1 hour by default; adjust expiration as needed.

Always validate and sanitize user input to avoid security issues.

Summary

Email verification confirms user ownership of an email address.

Use itsdangerous.URLSafeTimedSerializer to create and check tokens.

Send users a link with a token to verify their email safely and simply.