I want to generate an unsubscribe link that a user can click when receiving an email to unsubscribe that address. I don't want to just include the email in the link because a user could edit the link to unsubscribe someone else. Most emails I see generate some sort of token and the site knows how to match the token to the user. How can I generate such a token with Flask?
for email in email_lst:
body = 'unsubscribe link with token'
msg.attach(MIMEText(body, 'html'))
more code to send email
Flask includes the library itsdangerous which is used to generate tokens by securely signing serialized data.
For each email, generate a token with the email to be unsubscribed, and create an unsubscribe
route that accepts and decodes that token to determine who to unsubscribe.
from itsdangerous import URLSafeSerializer, BadData
@app.route('/unsubscribe/<token>')
def unsubscribe(token):
s = URLSafeSerializer(app.secret_key, salt='unsubscribe')
try:
email = s.loads(token)
except BadData:
# show an error
...
# unsubscribe
...
def send_email():
s = URLSafeSerializer(app.secret_key, salt='unsubscribe')
token = s.dumps(user.email)
url = url_for('unsubscribe', token=token)
# add the url to your message
...
Since the token is signed, a user can see the data but can't change it without invalidating the token.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With