Search code examples
python-3.6django-2.0

Django 2 email unsubscribe link


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


Solution

  • 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, '[email protected]', [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.