11

I'm using this code to send email from a web application. No problem with just one recipient. I've researched to use the same technic coming from https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/csharp.html to send email to multiple recipients. I tried whith a comma delimited string as destinatario (see args in the code) i.e. you@example.com, she@example.com, he@example.com but SendGrid takes the first one recipient only. I also tried using an array but the result is simmilar, SG takes the last recipient only. What is the correct way to pass the list of recipients?

public class email
{
    public void enviar(string destinatario, string asunto, string contenido)
    {
        Execute(destinatario, asunto, contenido).Wait();
    }

    static async Task Execute(string destinatario, string asunto, string contenido)
    {
        string apiKey = "SG...............";
        dynamic sg = new SendGridAPIClient(apiKey);

        Email from = new Email("someone@example.com");
        string subject = asunto;
        Email to = new Email(destinatario);
        Content content = new Content("text/plain", contenido);           

        Mail mail = new Mail(from, subject, to, content);
        dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
    }


}
kk.
  • 3,747
  • 12
  • 36
  • 67
mainavatar
  • 111
  • 1
  • 1
  • 3

5 Answers5

12

You need to add the Personalizations list for that. Following code works for me.

var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
    From = new EmailAddress("sender@email.com", "Sender Name"),
    Subject = "Subject",
    PlainTextContent = "Text for body",
    HtmlContent = "<strong>Hello World!",
    Personalizations = new List<Personalization>
    {
         new Personalization
         {
              Tos = new List<EmailAddress> 
              {
                   new EmailAddress("abc@email.com", "abc"),
                   new EmailAddress("efg@email.com", "efg")
              }
         }
     }
};

var response = await client.SendEmailAsync(msg);

For more details check following Mail Send

reza.cse08
  • 5,938
  • 48
  • 39
3
public static SendGridMessage CreateSingleEmailToMultipleRecipients(EmailAddress from, List<EmailAddress> tos, string subject, string plainTextContent, string htmlContent, bool showAllRecipients = false);
demo
  • 6,038
  • 19
  • 75
  • 149
digish a d
  • 441
  • 1
  • 6
  • 10
2

Below code worked for me

using SendGrid;
using SendGrid.Helpers.Mail;

public async Task<bool> sendEmailMonthlyReports(List<string> emailAddress, string filePath)
{
try
{
    var client = new SendGridClient("API Key");
    var msg = new SendGridMessage()
    {
        From = new EmailAddress("from@xxxx.com", "xxxxx"),
        Subject = "xxxx",
        HtmlContent = ""
    };

    var tosList = new List<EmailAddress>();
    if (emailAddress.Count() > 0)
    {
        foreach (var i in emailAddress)
        {
            tosList.Add(new EmailAddress(i));
        }
    }

// you can skip this attachment part if you don't have attachments

        using (var webClient = new WebClient())
        {
            if (filePath != null && filePath != "")
            {
                var bytes = webClient.DownloadData(filePath);
                var file = Convert.ToBase64String(bytes);
                msg.AddAttachment("exx.pdf", file);
             }
        }

    var result2 = MailHelper.CreateSingleEmailToMultipleRecipients(msg.From,tosList,msg.Subject,"",msg.HtmlContent);
    result2.Attachments = msg.Attachments;
    msg.SetClickTracking(false, false);

    var result = await client.SendEmailAsync(result2);
    if (result.StatusCode.ToString() == "Accepted")
    {
        return true;
    }
    return false;
}
catch (Exception ex)
{
    var exe = ex.ToString();
    return false;
}
}
Raj
  • 385
  • 2
  • 15
  • Same for me. Using MailHelper. Even for single recipient using c# for the API v3 I was only able to send emails using the MailHelper.CreateSingleEmail(...) like shown here in my answer-> https://stackoverflow.com/a/73973828/3839019 – Danilo Marques Oct 06 '22 at 12:31
1

The answer to your question can be found in the library's source code, there are two constructors to create a Mail object. The constructor you're using is only suitable for sending mails to one recipient as you've stated. You have to use the parameterless constructor.

var mail = new Mail();
mail.Subject = "subject";
mail.From = new Email("from@example.com", "fromName");
mail.AddContent(new Content("text/html", "<p>this is a mail<p>"));
mail.AddPersonalization(personalization);

The actual recipients are added through the Personalization object:

var personalization = new Personalization();
foreach (Email email in emailList)
{
    personalization.AddTo(email);
}

This personalization object also allows more customization like adding recipients as cc or bcc.

Bonnoj
  • 53
  • 5
0

Send mail syntax for multiple recipients :

Namespace:

using SendGrid;
using SendGrid.Helpers.Mail;

Syntax:

var client = new SendGridClient("XXXXXXX");
var msg = new SendGridMessage() {
  From = new EmailAddress("Yourmail@address", " your Address name"),
    Subject = subject,
    PlainTextContent = message,
    HtmlContent = message
};

var timeToSend = DateTime.Now

// to add time to datetime refer  https://stackoverflow.com/questions/2146296/adding-a-time-to-a-datetime-in-c-sharp

if (timeToSend != null && timeToSend.Value.Date >= DateTime.Now.Date) {
  var offset = new DateTimeOffset(timeToSend.Value);
  long sendAtUnixTime = offset.ToUnixTimeSeconds();
  msg.SendAt = sendAtUnixTime;
}
var emails = to.Split(';');
foreach(var email in emails) {
  msg.AddTo(new EmailAddress(email));
}
if (!string.IsNullOrEmpty(bcc)) {
  msg.AddBcc(new EmailAddress(bcc));
}
var response = await client.SendEmailAsync(msg);
FoxyError
  • 694
  • 1
  • 4
  • 19
PrashSE
  • 177
  • 1
  • 4