Sending an email batch with SendGrid v3

Viewed 866

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?

2 Answers

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.

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 ...     
}
Related