How to Send Emails with Multiple Categories via SendGrid in C#?

It is somewhat hidden in the documentation, but you can send emails with multiple categories if you install SendGrid package with Version 1.2.1 in your C# project.

Here is a sample code:

public void SendHTMLEmailCategory(MailMessage msgMail, List<string> recipients, string sender, IEnumerable<string> categories)
{
//create a new message object
var message = SendGridMail.SendGrid.GetInstance();

//We want to add the recipients to the X-SMTPAPI header
message.Header.AddTo(recipients);

//Even though we added recipients to the Header, the envelope must also have a valid recipient
message.AddTo("xxxx@yyyy.com");

//set the sender
message.From = new MailAddress(sender);

//set the message body
message.Html = msgMail.Body;

//set the message subject
message.Subject = msgMail.Subject;

message.SetCategories(categories);

//create an instance of the Web transport mechanism
var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password));

//send the mail
transportInstance.Deliver(message);
}

 

For some reason, SendGrid has a dependency on the following packages:

  • Microsoft.Net.Http (Microsoft HTTP Client Libraries)
  • Microsoft.Bcl.Async (Microsoft Async)

All dependent projects MUST also install these packages.  When I did an upgrade, it impacted many projects.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s