Custom Tokens in Email Campaign Manager

Recently I had a requirement from a client where they wanted to use Sitecore Email Campaign Manager to send registration emails, containing registration details and other dynamic custom data. Here is how to create tokens within a Email Campaign message and replace them with variables in a manually triggered email.

  1. Add your token(s) into the body text of the campaign message in the format $key$, ensure that the key text is lower case.

    Sitecore Custom Tokens
    Sitecore Email Campaign Manager Custom Tokens
  2. Get the message using the Sitecore API, replace the variables using the CustomPersonTokens dictionary and then trigger the send pipeline. The CustomPersonToken dictionary requires the key to be in lower case and requires the surrounding $$ to be removed.
//Get the message using the Sitecore API
var mi = Sitecore.Modules.EmailCampaign.Factory.GetMessage(messageId);

//Use the custom person token dictionary to replace the key with a string variable. Remember that the token key has to be lower case and remove the $$ surrounding the key
 mi.CustomPersonTokens.Add("username", "MikeTest");

//Send the message
new AsyncSendingManager(mi).SendStandardMessage(contactFromName);

Trigger Email and Replace tokens

Here is a reusable function that allows you to send an email campaign message from code and replace custom tokens.

public void SendEmailCampaignMessage(ID messageId, string userName, Dictionary<string, string> customTokens = null)
        {
            var mi = Sitecore.Modules.EmailCampaign.Factory.GetMessage(messageId);

            if (customTokens != null)
            {
                foreach (var token in customTokens)
                {
                    mi.CustomPersonTokens.Add(token.Key, token.Value);
                }
            }

            var contactFromName = Contact.FromName(userName);

            new AsyncSendingManager(mi).SendStandardMessage(contactFromName);
        }