Search code examples
c#sendgridsendgrid-api-v3

How to send personalized emails using Sendgrid API C#


I want to have one API call send to a list of recipients and customize each email. I have the general code worked out. The substitutions are working. But this only sends to the first email address even though I have 2 personalizations with different email addresses.

        SendGridClient client = new SendGridClient(apiKey);
        SendGridMessage msg = new SendGridMessage();
        msg.SetFrom(new EmailAddress(from, fromName));
        msg.Subject = subject;
        msg.HtmlContent = some content with replacement fields
        List<string> recipients = new List<string>();
        recipients.Add("some address");
        recipients.Add("second address");

        msg.Personalizations = new List<Personalization>();
        for (int x = 0; x < recipients.Count; x++) {
            if (recipients[x].IndexOf("@") > -1) {
                //msg.AddTo(recipients[x]);
                Personalization personalization = new Personalization();
                personalization.Tos = new List<EmailAddress> { new EmailAddress(recipients[x]) };
                Dictionary<string, string> subs = new Dictionary<string, string>();
                subs.Add("[Verification Code]", "ABC123");
                subs.Add("[User Name]", "Mark");
                personalization.Substitutions = subs;
                msg.Personalizations.Add(personalization);
                addressAdded = true;
            }
        }
        Response response = await client.SendEmailAsync(msg).ConfigureAwait(false);

What am I doing wrong? Is there some documentation on this?


Solution

  • IsValidEmail Method:

        public static bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
    

    SendEmail Method:

        SendGridClient client = new SendGridClient(apiKey);
        SendGridMessage msg = new SendGridMessage();
        msg.SetFrom(new EmailAddress(from, fromName));
        msg.Subject = subject;
        msg.HtmlContent = "<strong> C# is the Best! </strong>";
        List<string> recipients = new List<string>();
        recipients.Add("some address");
        recipients.Add("second address");
    
        msg.Personalizations = new List<Personalization>();
    
        foreach (string recipient in recipients)
        {
            if (IsValidEmail(recipient))
            {
                Personalization personalization = new Personalization();
                personalization.Tos = new List<EmailAddress>();
    
                personalization.Tos.Add(new EmailAddress(recipient));
                msg.Personalizations.Add(personalization);
    
                Dictionary<string, string> subs = new Dictionary<string, string>();
                subs.Add("{{UserName}}", "Mark");
                subs.Add("{{VerificationCode}}","ABC123");
    
                personalization.Substitutions = subs;
                msg.Personalizations.Add(personalization);
    
                addressAdded = true;
            }
    
            // This Worked
            if (addressAdded)
            {
                Response response = await client.SendEmailAsync(msg);
                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Headers.ToString());
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            }
        }