Engineering · Common · Sitecore

Unsubscribe email in Sitecore EXM

Sometimes you need to unsubscribe a contact programmatically. For example, you have a legacy third-party email management system and whenever a user unsubscribes from an email in that system, you want to add them to your Sitecore EXM unsubscribe list. There are a few challenges. First, how will we know someone has unsubscribed? Second, we don’t know if this email address exists in our contact list or not. The third challenge is how to add this contact to our Common Global Opt-out list.

Regarding the first challenge, we have to expose an API in our Sitecore website that will be consumed by the third-party email system. So, whenever a user unsubscribes from an email, that system will send that contact information through this API to Sitecore. The contact information is mainly the email address, first name and last name. There are plenty of articles on how to expose an API; I found the following one useful:

https://briancaos.wordpress.com/2018/06/22/sitecore-and-webapi/

Now, coming to the second challenge, it is not straightforward to search for a contact in Sitecore by email address, because it is PII-sensitive data and indexing is disabled by default. If you want to enable it, please go through the following article:

https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/enable-indexing-of-pii-sensitive-data-in-the-xdb-index.html

So, rather than searching by email, we can search for the contact by identifier and use the email as the identifier. If we can’t find any, we will create a new contact. To start with, we need an “XConnectClient” block; all our code will be inside the try block:

Our API will accept a Contact model as follows:

We have to create an identifier and check whether it exists:

If the contact does not exist, we have to create a new one:

If it’s a new contact, we should create a new contact facet as well. This new facet will contain First Name, Last Name, and Email. If we don’t create a facet, our contact will not have information about the name or email.

Now that we have the contact, we add the contact to our Common Global Opt-out list. (ISubscriptionService can be found in Sitecore.ListManagement.XConnect.Web.)

Now, if you create a new email campaign, the emails on the opt-out list will be excluded from the recipient lists.

Thanks