Sitecore: Programmatically adding contacts to a list
From Sitecore 8 the EXM module now uses lists to manage mailing lists rather than roles against a user. The built in Subscription form control that comes with EXM has also been updated to add contacts to this list. However the subscription control remains WebForms only, so if you implementing an MVC solution you're going to need to write your own. There's also many other scenarios where you may want to programmatically create and add a contact to a list.
Under the hood, contact lists aren’t even a list at all. Rather they are actually just a Facet on the Contact record that contains the list id's for all the lists the contact is a part of. You can see this by looking in the contacts collection in the analytics mongo db.
Or in the Contacts table in the Reporting SQL db.
If you wanted to add a contact to a list you could in theory just add the relevant tag to the contact record like this:
1public void AddContactToList(Contact contact, Item list)2{3 using (new SecurityDisabler())4 {5 contact.Tags.Set("ContactLists", list.ID.ToString());6 }7}
But I wouldn't. The problem with this approach is your going to miss out any logic that will handle updating the counts of contacts in contact lists. Best to use one of the provided list api's instead.
Adding a contact to a list
Sitecore has a ContactListManager object that has a method to associate contacts with lists. All you need to do is create an instance of it and pass it a list of contacts.
1public void AddContactToList(ContactData contact, ContactList list)2{3 ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;45 List<ContactData> contactList = new List<ContactData>();6 contactList.Add(contact);78 listManager.AssociateContacts(list, contactList);9}
Removing a contact from a list
Just like adding a contact, there's also a handy method for removing one too.
1public void RemoveContactFromList(ContactData contact, ContactList list)2{3 ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;45 List<ContactData> contactList = new List<ContactData>();6 contactList.Add(contact);78 listManager.RemoveContactAssociations(list, contactList);9}
What's that ContactData object?
Chances are you don't have a ContactData object (Sitecore.ListManagement.ContentSearch.Model.ContactData) and instead probably have a tracking contact (Sitecore.Analytics.Tracking.Contact). For the purposes of adding and removing a contact from a list, all your ContactData object really needs is its identifier, which you can do with the following:
1public ContactData ConvertContactToContactData(Sitecore.Analytics.Tracking.Contact contact)2{3 return new ContactData()4 {5 Identifier = contact.Identifiers.Identifier6 };7}