Skip to content

How to: Use Merge Tags With the Mandrill .NET Wrapper

Christian Wattengård edited this page Apr 18, 2017 · 4 revisions

According to the Mandrill help page on merge tags, the syntax for a merge tag is *|TAG_NAME|*.

You can use the API to specify merge tags for either the global message or per-recipient.

Before You Begin

Templates are set up based on an EmailMessage object, so you should already have one of those in your code.

var mandrill = new MandrillApi("YourApiKey");
var mandrillRecipients = new List<EmailAddress>();
// add recipents to the mandrillRecipientsList
var email = new EmailMessage
  {
    to = mandrillRecipients,
    from_email = "you@yoursite.com",
    from_name = "MyCompany Support",
  };

Adding Global Merge Tag Variables

These variables will be substituted the same for all recipients.

For example, if in your Mandrill template, you had:

Please contact our support team at *|SUPPORT_TEAM_EMAIL|*.

Then in the API, you could add a global variable like so:

email.AddGlobalVariable("SUPPORT_TEAM_EMAIL", "support@mysite.com");

All users would then receive this variable.

Adding Recipient-based Merge Tag Variables

If you used a *|USER_NAME|* merge tag in your e-mail, like so:

Dear *|USER_NAME|*,

You would want to make sure every recipient had their own variable.

To do this in your code, you'd probably want to create some sort of a for loop for each e-mail address and their username:

foreach (var user in listOfUsers)
{
   email.AddRecipientVariable(user.emailAddress, "USER_NAME", user.UserName);
}

This would substitute the merge tag value only for the specific e-mail address that you specify in the first variable.

Sending the Merge Email

To send the email, you would send it via:

mandrill.SendMessage(email, "your-template-slug-name", null); //null is for template contents, since we did not use any.

References