How to Send Email Using SendGrid with Azure

Overview

This guide demonstrates how to perform common programming tasks with the SendGrid email service on Azure. The samples are written in C# and use the .NET API. The scenarios covered include constructing email, sending email, adding attachments, and using filters. For more information on SendGrid and sending email, see the Next steps section.

What is the SendGrid email service?

SendGrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with flexible APIs that make custom integration easy. Common SendGrid usage scenarios include:

  • Automatically sending receipts to customers.
  • Administering distribution lists for sending customers monthly e-fliers and special offers.
  • Collecting real-time metrics for things like blocked email, and customer responsiveness.
  • Generating reports to help identify trends.
  • Forwarding customer inquiries.
  • Processing incoming emails.

For more information, see https://sendgrid.com or our C# library

Create a SendGrid account

Azure customers can unlock 25,000 free emails each month. These 25,000 free monthly emails will give you access to advanced reporting and analytics and all APIs (Web, SMTP, Event, Parse and more). For information about additional services provided by SendGrid, see the SendGrid Features page.

To sign up for a SendGrid account

  1. Log in to the Azure Management Portal.
  2. In the lower pane of the management portal, click New.

    command-bar-new

  3. Click Marketplace.

    sendgrid-store

  4. In the Choose an Application and Service dialog, select SendGrid and click the right arrow.
  5. In the Personalize Application and Service dialog select the SendGrid plan you want to sign up for.
  6. Enter a name to identify your SendGrid service in your Azure settings, or use the default value of SendGridEmailDelivery.Simplified.SMTPWebAPI. Names must be between 1 and 100 characters in length and contain only alphanumeric characters, dashes, dots, and underscores. The name must be unique in your list of subscribed Azure Store Items.

    store-screen-2

  7. Choose a value for the region; for example, West US.
  8. Click the right arrow.
  9. On the Review Purchase tab, review the plan and pricing information, and review the legal terms. If you agree to the terms, click the check mark. After you click the check mark, your SendGrid account will begin the SendGrid provisioning process.

    store-screen-3

  10. After confirming your purchase you are redirected to the add-ons dashboard and you will see the message Purchasing SendGrid.

    sendgrid-purchasing-message

    Your SendGrid account is provisioned immediately and you will see the message Successfully purchased Add-On SendGrid. Your account and credentials are now created. You are ready to send emails at this point.

    To modify your subscription plan or see the SendGrid contact settings, click the name of your SendGrid service to open the SendGrid Marketplace dashboard.

    sendgrid-add-on-dashboard

    To send an email using SendGrid, you must supply your account credentials (username and password).

To find your SendGrid credentials

  1. Click Connection Info.

    sendgrid-connection-info-button

  2. In the Connection info dialog, copy the Password and Username to use later in this tutorial.

    sendgrid-connection-info

    To set your email deliverability settings, click the Manage button. This will redirect to your SendGrid Control Panel.

    sendgrid-control-panel

    For more information on getting started with SendGrid, see SendGrid Getting Started.

Reference the SendGrid .NET class library

The SendGrid NuGet package is the easiest way to get the SendGrid API and to configure your application with all dependencies. NuGet is a Visual Studio extension included with Microsoft Visual Studio 2015 that makes it easy to install and update libraries and tools.

Note

To install NuGet if you are running a version of Visual Studio earlier than Visual Studio 2015, visit http://www.nuget.org, and click the Install NuGet button.

To install the SendGrid NuGet package in your application, do the following:

  1. Created a new project.

    Create a new project

  2. Select a template.

    Select a template

  3. In Solution Explorer, right-click References, then click Manage NuGet Packages.
  4. Search for SendGrid and select the SendGrid item in the results list.

    SendGrid NuGet package

  5. Select version 6.3.4 of the Nuget package from the version dropdown to be able to work with the object model and APIs demonstrated in this article
  6. Click Install to complete the installation, and then close this dialog.

SendGrid's .NET class library is called SendGridMail. It contains the following namespaces:

  • SendGridMail for creating and working with email items.
  • SendGridMail.Transport for sending email using either the SMTP protocol, or the HTTP 1.1 protocol with Web/REST.

Add the following code namespace declarations to the top of any C# file in which you want to programmatically access the SendGrid email service. System.Net and System.Net.Mail are .NET Framework namespaces that are included because they include types you will commonly use with the SendGrid APIs.

using System;
using System.Net;
using System.Net.Mail;
using SendGrid;

How to: Create an email

Use the SendGridMessage object to create an email message. Once the message object is created, you can set properties and methods, including the email sender, the email recipient, and the subject and body of the email.

The following example demonstrates how to create a fully populated email object:

// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();

// Add the message properties.
myMessage.From = new MailAddress("john@example.com");

// Add multiple addresses to the To field.
List<String> recipients = new List<String>
{
    @"Jeff Smith <jeff@example.com>",
    @"Anna Lidman <anna@example.com>",
    @"Peter Saddow <peter@example.com>"
};

myMessage.AddTo(recipients);

myMessage.Subject = "Testing the SendGrid Library";

//Add the HTML and Text bodies
myMessage.Html = "<p>Hello World!</p>";
myMessage.Text = "Hello World plain text!";

For more information on all properties and methods supported by the SendGrid type, see sendgrid-csharp on GitHub.

How to: Send an email

After creating an email message, you can send it using the Web API provided by SendGrid. Alternatively, you may use .NET's built in library.

Sending email requires that you supply your SendGrid account credentials (username and password) or SendGrid API Key. API Key is the preferred method. If you need details about how to configure API keys, please visit our documentation

You may store these credentials via your Azure Portal by clicking CONFIGURE and adding the key/value pairs under "app settings".

Azure app settings

Then, you may access them as follows:

var username = System.Environment.GetEnvironmentVariable("SENDGRID_USERNAME"); 
var pswd = System.Environment.GetEnvironmentVariable("SENDGRID_PASSWORD");
var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");

Using Credentials:

// Create network credentials to access your SendGrid account
var username = "your_sendgrid_username";
var pswd = "your_sendgrid_password";

var credentials = new NetworkCredential(username, pswd);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);

Using API Key:

var apiKey = "your_sendgrid_api_key";  
// create a Web transport, using API Key
var transportWeb = new Web(apiKey);

The following examples show how to send a message using the Web API.

// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";

// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("username", "password");

// Create an Web transport for sending email.
var transportWeb = new Web(credentials);

// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage);

// If developing a Console Application, use the following
// transportWeb.DeliverAsync(mail).Wait();

How to: Add an attachment

Attachments can be added to a message by calling the AddAttachment method and specifying the name and path of the file you want to attach. You can include multiple attachments by calling this method once for each file you wish to attach. The following example demonstrates adding an attachment to a message:

SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";

myMessage.AddAttachment(@"C:\file1.txt");

You can also add attachments from the data's Stream. It can be done by calling the same method as above, AddAttachment, but by passing in the Stream of the data, and the filename you want it to show as in the message. In this case you will need to add the System.IO library.

SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";

using (var attachmentFileStream = new FileStream(@"C:\file.txt", FileMode.Open))
{
    myMessage.AddAttachment(attachmentFileStream, "My Cool File.txt");
}

How to: Use apps to enable footers, tracking, and analytics

SendGrid provides additional email functionality through the use of apps. These are settings that can be added to an email message to enable specific functionality such as click tracking, Google analytics, subscription tracking, and so on. For a full list of apps, see App Settings.

Apps can be applied to SendGrid email messages using methods implemented as part of the SendGrid class.

The following examples demonstrate the footer and click tracking filters:

// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";

// Add a footer to the message.
myMessage.EnableFooter("PLAIN TEXT FOOTER", "<p><em>HTML FOOTER</em></p>");

Click tracking

// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("anna@example.com");
myMessage.From = new MailAddress("john@example.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Html = "<p><a href=\"http://www.example.com\">Hello World Link!</a></p>";
myMessage.Text = "Hello World!";

// true indicates that links in plain text portions of the email 
// should also be overwritten for link tracking purposes. 
myMessage.EnableClickTracking(true);

How to: Use additional SendGrid services

SendGrid offers web-based APIs and webhooks that you can use to leverage additional SendGrid functionality from your Azure application. For full details, see the SendGrid API documentation.

Next steps

Now that you've learned the basics of the SendGrid Email service, follow these links to learn more.