Allowing your users to unsubscribe from your email notifications in MVC3 and Entity Framework

This is a step by step list of all the steps I took to be able to add a “Unsubscribe” link in the signature of the emails Week Plan sends to the users.

Of course, users must be unsubscribed even when they are not logged in.

This is how I went about it (took me 30mins).

1. Modify the models

First I have added a boolean “BlockedEmails” and a Guid “Guid” property in the User table.

Because I use Code First Entity Framework and Automatic Migrations, I don’t have to take any additional step to make sure the database will be upgraded as well.

2. Autopopulating the value of the Guid

In the mapping class of the User model, I simply need to add the following line:

this.Property(o => o.Guid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

How simple!

Now, I want to add an Unsubscribe link in the emails being sent. The link would follow this format:

3. Adding the Action in the Account controller

This is just two lines of code:

As you can guess, the UnsubscribeFromEmails search for a user with the same Guid as the id parameter and sets BlockedEmails to true.

The rest is basic MVC development:

  • I added a Unsubscribed view in the Views/Account folder.

  • I added the Unsubscribe link inside the email.

  • I don’t send emails to users who have their BlockedEmails set to true.

Thank you for reading.