How to use custom tokens in EXM while sending emails from code?

In this post I’d like to discuss

  • How to use custom tokens in EXM while sending emails from code?

If you are sending an email from code and would like to personalize an email; you can build Sitecore EXM’s email template with tokens or parameters, values for which will be replaced during email send. Sitecore’s OOTB tokens are documented here . As you can see this is quite flexible, and can be extended to include custom  contact facets. However, sometimes it’s not feasible to build custom facets, or the requirement is to fetch data from external sources. In my previous post, I have described how to send an EXM email from code. Adding custom tokens is a simple extension to that.

First we need to build an email template with a custom token

 

 

Next, we’ll update the send message method to include the custom token replacement code:

        public void Send(ID messageItemId, string email, Dictionary<string, object> customPersonsTokens)
        {
            // retrive message item from Sitecore
            var message = Factory.GetMessage(messageItemId);
            // for multi lingual solution use the override to get the correct language version
            //var message = Factory.GetMessage(messageItemId,"en");
            Assert.IsNotNull(message, $"Could not find message with ID {messageItemId}");
            RecipientId recipient = GetXdbContactId(email);
            Assert.IsNotNull(recipient, $"Could not find recipient with email {email} in xDB");

            foreach (var customPersonToken in customPersonsTokens as IEnumerable<KeyValuePair<string, object>>)
            {
                message.CustomPersonTokens[customPersonToken.Key] = customPersonToken.Value;
            }
            // sync call
            //var sendingManager = new SendingManager(message);
            //sendingManager.SendStandardMessage(recipient);
            var asyncSending = new AsyncSendingManager(message);
            asyncSending.SendStandardMessage(recipient);
        }

 

Finally, we’ll invoke the new method, with the token replacement. In my example I am hard coding the value, but you can replace this with data from an API, custom database or any other source.

   public ActionResult SendEmailToUser(string email)
        {
            var customPersonsToken = new Dictionary<string, object>
            {
                {"CustomTokenExample", $"Custom Token was replaced for {email}"}
            };
            _exmMessageService.Send(ID.Parse("{4E9F9E07-ACBD-4042-B173-B9C64F001048}"), email, customPersonsToken);
            return new EmptyResult();
        }

You can download the code from here

How to use custom tokens in EXM while sending emails from code?
Tagged on:         

One thought on “How to use custom tokens in EXM while sending emails from code?

Leave a Reply

Your email address will not be published. Required fields are marked *