Django 2 email unsubscribe link

一曲冷凌霜 提交于 2019-12-11 15:14:21

问题


I want to add an unsubscribe link in emails being sent to the user. I am unsure on how to achieve it. I want the user to be able to unsubscribe without having to log in. Any suggestions on how to achieve this would be appreciated. Thanks


回答1:


I'll assume you know how to send an email with django, and other basic things.

For every email you send to them, you have to build the unsubscribe link first, like the following. Note that the following has a url pattern, and a model that takes a uuid field (uuid4 to be specific, because it's the safest one). The reason why you want to do it this way is so random people can't go to YourWebsite.com/unsub_email/1, /2, /3, /4, etc, and unsub as many people as they possibly can by guessing the number. By doing it the way I show, there's something like a chance of 1 in 100, with like 50+ zero's after it that they would even get 1. So it's safer.

def send_user_an_email(id_of_your_object):
    users_email = UsersEmail.objects.get(id=id_of_your_object)
    unsub_link = 'https://www.YourWebsite.com/unsub_email/{}/{}/'.format(users_email.id, users_email.random_uuid)
    subject = 'Your subject line.'
    message = 'Your message body.\n\nGo here to unsubscribe: {}'.format(unsub_link)
    mail_sent = send_mail(subject, message, 'DoNotReply@YourWebsite.com', [users_email.users_email_char_field])
    return mail_sent

Then you just write a function to let them click a button on that page, and they get unsubbed, or however else you want to do it. An even safer option would be to show them a valid unsub page, but make them type out their email again, but don't show them the email related to the valid url pattern. That extra step would make it that much harder for someone who'd want to write a bad script to unsub everyone on your list.



来源:https://stackoverflow.com/questions/52033642/django-2-email-unsubscribe-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!