There could be a scenario when you might need to unsubscribe contact programmatically. For example, you have a legacy third-party email management system and whenever a user unsubscribes an email in that system, you want to add them to your Sitecore EXM unsubscribe list. There are a few challenges, firstly, how we will know someone has unsubscribed? Secondly, 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 an email that system will send that contact information through this API to Sitecore. Contact information mainly Email address, First Name, Last Name. How to expose an API, there are a lot of articles on it, I found the following is a good one

Now, coming to the second challenge, it is not straightforward to search 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:

So, rather than search by email, we can try to search the contact by identifier and we will consider email as an identifier. If we can’t find any, we will create a new contact. To starts with, we will 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 if it exists or not

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

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.

We got the contact and now, we are going to add the contact to our Common Global Opt-out list. (here, ISubscriptionService can be found in Sitecore.ListManagement.XConnect.Web)

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


Next post Dependency Inversion Principle and the Dependency Injection Pattern