Search code examples
c#sendgridsendgrid-templates

Sendgrid substitution works only for the first recipient


I am using Sendgrid to send emails with templates that contain multiple variables. Everything works well when I have only one recipient for an email.

When I have multiple recipients either in To or one in To and one in Cc, the first email is ok but the following have empty strings in the substition tags.

Below is my code :

private bool SendEmail(MailAddress from, string[] to, string template, Dictionary<string, string> keyToReplace, string[] cc = null)
{
        var message = new SendGridMessage();
        message.From = from;
        message.AddTo(to);

        if (cc != null && cc.Any())
        {
            foreach (var ccAddress in cc)
            {
                message.AddCc(ccAddress);
            }
        }

        message.Subject = " ";
        message.Text = string.Empty;
        message.Html = "<p></p>";
        message.EnableTemplate("<%body%>");
        message.EnableTemplateEngine(templateIds[template]);

        foreach (var keyValue in keyToReplace)
        {
            var key = keyValue.Key;
            if (!key.StartsWith("#"))
            {
                key = string.Format("#{0}#", key);
            }
            var value = keyValue.Value;
            if (string.IsNullOrEmpty(keyValue.Value))
            {
                value = " ";
            }
            message.AddSubstitution(key, new List<string> { value });
       }
       var transportWeb = transportFactory(credentials);
       transportWeb.Deliver(message);
       logger.Info("Mail sent to : " + string.Join(", ", to));
       return true;
  }

Solution

  • I enventually updated the Sendgrid nuget package from version 5.0.0 to version 9.5.0 and it fixed the issue.