Sitecore EXM Programmatically sending email along with adding contact to list

This post will get the user details from the Form and add these user details as a Contact to XDB, and it will trigger the EXM automated email that I have created in Sitecore after this contact was added to the ListManger.

Steps to be done before getting hands dirty.

  • Create an empty contact list using ListManager
  • Create an Automated Email Campaign message in EXM(Choose this to send an email campaign, for example, when a visitor triggers a goal or event on your website. Rule triggers Email Message on event)
  • Create Custom Facet that will hold all the user details received through the Form.Refer my post for Custom contact Facet


Let's start adding contacts to the List and send an Email.

        public void AddContactToListAndSendEmail()
        {
            string emailAddress = "nels_jnjr4@yahoo.com";
            ContactRepository contactRepository = Sitecore.Configuration.Factory.CreateObject("tracking/contactRepository", true) as ContactRepository;
            var contact = contactRepository.LoadContactReadOnly(emailAddress);
            ContactManager contactManager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as ContactManager;
            LockAttemptResult<Contact> lockResult;
            if (contact == null)
            {
                lockResult = new LockAttemptResult<Contact>(LockAttemptStatus.NotFound, null, null);
                contact = contactRepository.CreateContact(Sitecore.Data.ID.NewID);
                contact.Identifiers.AuthenticationLevel = Sitecore.Analytics.Model.AuthenticationLevel.None;
                contact.Identifiers.Identifier = emailAddress;
                contact.Identifiers.IdentificationLevel = ContactIdentificationLevel.Known;
                contact.System.Value = 0;
                contact.System.VisitCount = 0;
                contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
                contactManager.FlushContactToXdb(contact);

            }
            else
            {
                lockResult = contactManager.TryLoadContact(contact.ContactId);
                contact = lockResult.Object;
            }
            var personal = contact.GetFacet<Sitecore.Analytics.Model.Entities.IContactPersonalInfo>("Personal");
            personal.FirstName = "nelson";
            personal.Surname = "J";
            var emailAddresses = contact.GetFacet<Sitecore.Analytics.Model.Entities.IContactEmailAddresses>("Emails");
            if (!emailAddresses.Entries.Contains("Email"))
            {
                emailAddresses.Entries.Create("Email");
            }
            var email = emailAddresses.Entries["Email"];
            email.SmtpAddress = emailAddress;
            emailAddresses.Preferred = "Email";
           //custom Facet refer the link Custom contact Facet
            var contactEmailAddresses = contact.GetFacet<IContactCommentsFacet>("Contact Details");
            if (!contactEmailAddresses.CustomerDetails.Contains("Contact Details"))
            {
                contactEmailAddresses.CustomerDetails.Create("Contact Details");
                contactEmailAddresses.CustomerDetails["Contact Details"].Age = "12";
                contactEmailAddresses.CustomerDetails["Contact Details"].Company = "TestCompany";
                contactEmailAddresses.CustomerDetails["Contact Details"].Designation = "Technical Lead";
                contactEmailAddresses.CustomerDetails["Contact Details"].Email = emailAddress;
            }
MediaItem mediaItem = Sitecore.Context.Database.GetItem("/sitecore/media library/Images/profile/nelson");
            var stream = mediaItem.GetMediaStream();
            var memoryStream = new MemoryStream();
            if (stream != null)
  stream.CopyTo(memoryStream);
            var contactImage = Tracker.Current.Contact.GetFacet<IContactPicture>("Picture");
            contactImage.Picture = memoryStream.ToArray();

            contactImage.MimeType = mediaItem.MimeType;
            ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;
            contactManager.SaveAndReleaseContactToXdb(contact);
            //Getting the Email Campaign ManagerRoot
            Item managerRoot = Sitecore.Data.Database.GetDatabase("master").GetItem("/sitecore/content/Email Campaign");
           
            RecipientId recipient = RecipientRepository.GetDefaultInstance().ResolveRecipientId("xdb:" + contact.ContactId);
            var recipientId = new Sitecore.Modules.EmailCampaign.Xdb.XdbContactId(contact.ContactId);
   // Adding contact to List

Sitecore.Modules.EmailCampaign.ClientApi.UpdateSubscriptions(recipientId, new[] { "{35858223-52DC-4785-E865-E164A01B0314}" }, new string[] { }, managerRoot.ID.ToString(), false);
              //Passing Message Item id and recipient           
           Sitecore.Modules.EmailCampaign.ClientApi.SendStandardMessage(new Guid("{0A096C12-A335-4970-A0BF-040A771579EB}"), recipient, true);
           // new AsyncSendingManager(message).SendStandardMessage(recipient); This method can be also used to send email message       
            Tracker.Current.Session.Identify(emailAddress);// Finally identify the anonymous contact with the contact we added to XDB
          

        }

Output:

We have added the contact to Mongo DB with all details along with a new contact to the List
.


Contact Added to list Manager:



Emails received:

In the next article, we will see about sending multilingual emails.

Comments

Popular posts from this blog

Custom Item Url and resolving the item in Sitecore - Buckets

Exploring Sitecore XM Cloud Forms: A Comprehensive Overview

Sitecore Custom Rule (Action and Condition)