Search code examples
c#templatesmandrill

C# Send email using Mandrill template 'foreach loop'


I am using mandrill template to send email in my web application . I have a "foreach loop" for my list of items where I want to auto generate template for the number of items.

how can I add foreach logic in my template and in c# for my back end code?

Assume I have two lists and I want to include all the list of items in my for each loop.

var itemList = new List<string>();
var itemList1 = new List<int>();

how can i create a loop for this scenario ?

foreach (var each in itemList){}

Solution

  • You can use Tuple instead of using two lists separately.

    this is what your C# logic for sending emails using template //C#

    var itemContainerTuple = new List<Tuple<string, int?>>();
    var mandrill = new MandrillApi(ConfigurationManager.AppSettings["MandrillApiKey"]);
    var emailMessage = new EmailMessage
     {
        FromEmail = "youremail",
        To = new List<EmailAddress> { new EmailAddress { Email = "senderEmail" } },
        Subject = "your subject",
        FromName = "Yourname",
        MergeLanguage = "handlebars",
        Merge = true,
     };
    
        emailMessage .AddGlobalVariable("ItemContainer", itemContainerTuple);
        await mandrill.SendMessageTemplate(new SendMessageTemplateRequest(emailMessage , "YourTemplateName"));
    

    In your Mandrill template You can try like that -

    //Template
    // for each row from tuple string would be red and int would be black. 
    
    {{#each ItemContainer}}   
      <li>
       <span style="color:red"><strong>{{Item1}}</strong></span>         
      </li>
    
      <li>
       <span style="color:black"><strong>{{Item2}}</strong></span>         
      </li>
    {{/each}}