3

I have a usecase where I have 1000 emails with the bodies prepared (they are ready to send as is), a single sent from email address, 1000 recipients. I am using SendGrid API v3 in C#. I am trying to figure out how to bulk send them to the SendGrid API. This is my code:

 private async Task SendBatchEmails(DataRowCollection emailDataRows)
        {
            var WriteToDatabaseCollection = new Dictionary<Guid, string>();
            var emailObjectCollection = new List<SendGridMessage>();

            foreach (DataRow emailDataRow in emailDataRows)
            {
                var emailObject = new SendGridMessage();

                var to = (new EmailAddress(emailDataRow["RecipientEmailAddress"] + "", emailDataRow["RecipientName"] + ""));
                var from = new EmailAddress(emailDataRow["SenderEmailAddress"] + "", emailDataRow["SenderName"] + "");
                var subject = emailDataRow["Subject"] + "";
                var text = emailDataRow["MessageBody"] + "";
                var html = $"<strong>{emailDataRow["MessageBody"] + "" }</strong>";

                var msg = MailHelper.CreateSingleEmail(from, to, subject, text, html);
                emailObjectCollection.Add(msg);

            }

            await emailClient.SendBatchEmailsEmailAsync(emailObjectCollection);


            dataContext.UpdateEmailResult(WriteToDatabaseCollection);
        } 


    public async Task SendBatchEmailsEmailAsync(List<SendGridMessage> messages)
    {
        return await client.????(messages);
    }

client is a SendGridClient, and the only option I have is: SendEmailAsync(msg)

How do I send a batch fo sendgrid messages?

Compo
  • 36,585
  • 5
  • 27
  • 39
  • 1
    I have removed your batch-file tag. Please take a look at the description for your tags, before allocating them to your question. A batch file is a Windows, MS-DOS or OS/2 script, usually with a `.bat`, but more recently with a `.cmd` file extension. If you are having difficulty with batch file code, please feel free to reinstate the tag, but in doing so, please include a [mcve] of the batch file content you'd like us to provide assistance for a specific programming issue it exhibits. – Compo Aug 19 '21 at 16:03
  • Does this answer your question? [sendgrid multiple recipients c#](https://stackoverflow.com/questions/38725978/sendgrid-multiple-recipients-c-sharp) – Jonathan Aug 19 '21 at 18:31

2 Answers2

4

Twilio SendGrid developer evangelist here.

There isn't a batch email send for emails with different bodies. Though you can send the same body to multiple addresses.

To send your 1000 emails you need to loop through your list of messages and call the API once per message.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • 1
    Hi Phil, if I have hundreds or thousands of emails that I want to send (e.g. imagine that before each of my webinars I want to send a reminder email to all of my students), and they have personalized (i.e. unique) subjects and bodies, is it still the case that I can't just post an array of all of that data to a Sendgrid API endpoint in one request? It seems odd that I need to handle the looping on my server and send a request for each. Thanks for the update. – Ryan Jun 15 '22 at 13:20
  • I wonder if https://docs.sendgrid.com/for-developers/sending-email/substitution-tags from https://stackoverflow.com/a/35040850/470749 is what I need. – Ryan Jun 15 '22 at 13:28
  • 1
    Yeah, you can [create a dynamic template and then send the data with each personalization](https://docs.sendgrid.com/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates). – philnash Jun 15 '22 at 14:38
  • @philnash since you're an expert, can you take a quick look at my issue? https://stackoverflow.com/questions/76707901/sendgrid-sending-bulk-email-results-in-badrequest-error – Joe Jul 18 '23 at 15:55
-1

If any of the emails you want to send has same body as others (you can't bulk send emails with different content as mentioned in the other answer), you could group them by body and then send in chunks. SendGridClient takes max 1000 at a time, so you'd also need to check for that. With something like this:

public class Email
{
    string Content { get; }
    string Address { get; }
}

Your code to group, chunk and send your emails in batches (where emails is a collection of Email objects) would look something like this:

var client = new SendGridClient("123456APIKEY");
var senderEmail = "someEmail";
var groupedByContent = emails.GroupBy(x => x.Content, x => x.Address);

foreach(var group in groupedByContent)
foreach(var recipientsBatch in group.Chunk(1000))
{
    var message = new SendGridMessage();
    // This extra index is needed to create separate personalizations, if you don't want recipients to see each others email
    for (var i = 0; i < recipientsBatch.Length; i++)
        message.AddTo(new EmailAddress { Email = recipientsBatch[i] }, i);
    message.PlainTextContent = group.Key;
    message.SetFrom(senderEmail);
    var response = await client.SendEmailAsync(message);
    // response processing code ...     
}
Simon Katanski
  • 426
  • 5
  • 8
  • This is still making a single API call for every email being sent and is not batching. – Jason Bert Nov 07 '22 at 09:10
  • It is sending a single API call for multiple email addresses for the case, when the body of the email is same (no custom parameters per emails etc). The alternative is to sent 1 API call per email, with the same body. I think that's an improvement, and hopefully someone can find it useful as well. – Simon Katanski Nov 08 '22 at 11:15