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 supports .NET Standard 1.3. The scenarios covered include constructing email, sending email, adding attachments, and enabling various mail and tracking settings. 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 use cases include:

  • Automatically sending receipts or purchase confirmations to customers.
  • Administering distribution lists for sending customers monthly fliers and promotions.
  • Collecting real-time metrics for things like blocked email and customer engagement.
  • Forwarding customer inquiries.
  • Processing incoming emails.

For more information, visit https://sendgrid.com or SendGrid's C# library GitHub repo.

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, visit the SendGrid Solutions page.

To sign up for a SendGrid account

  1. Log in to the Azure Management Portal.
  2. In the menu on the left, click New.

    command-bar-new

  3. Click Add-ons and then SendGrid Email Delivery.

    sendgrid-store

  4. Complete the signup form and select Create.

    sendgrid-create

  5. Enter a Name to identify your SendGrid service in your Azure settings. 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.
  6. Enter and confirm your Password.
  7. Choose your Subscription.
  8. Create a new Resource group or use an existing one.
  9. In the Pricing tier section select the SendGrid plan you want to sign up for.

    sendgrid-pricing

  10. Enter a Promotion Code if you have one.
  11. Enter your Contact Information.
  12. Review and accept the Legal terms.
  13. After confirming your purchase you will see a Deployment Succeeded pop-up and you will see your account listed in the All resources section.

    all-resources

    After you have completed your purchase and clicked the Manage button to initiate the email verification process, you will receive an email from SendGrid asking you to verify your account. If you do not receive this email, or have problems verifying your account, please see this FAQ.

    manage

    You can only send up to 100 emails/day until you have verified your account.

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

    settings

    To send an email using SendGrid, you must supply your API Key.

To find your SendGrid API Key

  1. Click Manage.

    manage

  2. In your SendGrid dashboard, select Settings and then API Keys in the menu on the left.

    api-keys

  3. Click the Create API Key dropdown and select General API Key.

    general-api-key

  4. At a minimum, provide the Name of this key and provide full access to Mail Send and select Save.

    access

  5. Your API will be displayed at this point one time. Please be sure to store it safely.

To find your SendGrid credentials

  1. Click the key icon to find your Username.

    key

  2. The password is the one you chose at setup. You can select Change password or Reset password to make any changes.

To manage your email deliverability settings, click the Manage button. This will redirect to your SendGrid dashboard.

![manage][manage]

For more information on sending email through SendGrid, visit the [Email API Overview][Email API Overview].

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 and above 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. Click on New Project and select a Template.

    Create a new project

  2. In Solution Explorer, right-click References, then click Manage NuGet Packages.

    SendGrid NuGet package

  3. Search for SendGrid and select the SendGrid item in the results list.
  4. Select the latest stable version of the Nuget package from the version dropdown to be able to work with the object model and APIs demonstrated in this article.

    SendGrid package

  5. Click Install to complete the installation, and then close this dialog.

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

  • SendGrid for communicating with SendGrid’s API.
  • SendGrid.Helpers.Mail for helper methods to easily create SendGridMessage objects that specify how to send emails.

Add the following code namespace declarations to the top of any C# file in which you want to programmatically access the SendGrid email service.

using SendGrid;
using SendGrid.Helpers.Mail;

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:

var msg = new SendGridMessage();

msg.SetFrom(new EmailAddress("dx@example.com", "SendGrid DX Team"));

var recipients = new List<EmailAddress>
{
    new EmailAddress("jeff@example.com", "Jeff Smith"),
    new EmailAddress("anna@example.com", "Anna Lidman"),
    new EmailAddress("peter@example.com", "Peter Saddow")
};
msg.AddTos(recipients);

msg.SetSubject("Testing the SendGrid C# Library");

msg.AddContent(MimeType.Text, "Hello World plain text!");
msg.AddContent(MimeType.Html, "<p>Hello World!</p>");

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 SendGrid's API. Alternatively, you may use .NET's built in library.

Sending email requires that you supply your SendGrid API Key. If you need details about how to configure API Keys, please visit SendGrid's API Keys documentation.

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

Azure app settings

Then, you may access them as follows:

var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
var client = new SendGridClient(apiKey);

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

using System;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace Example
{
    internal class Example
    {
        private static void Main()
        {
            Execute().Wait();
        }

        static async Task Execute()
        {
            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var client = new SendGridClient(apiKey);
            var msg = new SendGridMessage()
            {
                From = new EmailAddress("test@example.com", "DX Team"),
                Subject = "Hello World from the SendGrid CSharp SDK!",
                PlainTextContent = "Hello, Email!",
                HtmlContent = "<strong>Hello, Email!</strong>"
            };
            msg.AddTo(new EmailAddress("test@example.com", "Test User"));
            var response = await client.SendEmailAsync(msg);
        }
    }
}

How to: Add an attachment

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

var banner2 = new Attachment()
{
    Content = Convert.ToBase64String(raw_content),
    Type = "image/png",
    Filename = "banner2.png",
    Disposition = "inline",
    ContentId = "Banner 2"
};
msg.AddAttachment(banner2);

How to: Use mail settings to enable footers, tracking, and analytics

SendGrid provides additional email functionality through the use of mail settings and tracking settings. These settings 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 the Settings Documentation.

Apps can be applied to SendGrid email messages using methods implemented as part of the SendGridMessage class. The following examples demonstrate the footer and click tracking filters:

The following examples demonstrate the footer and click tracking filters:

msg.SetFooterSetting(
                     true,
                     "Some Footer HTML",
                     "<strong>Some Footer Text</strong>");

Click tracking

msg.SetClickTracking(true);

How to: Use Additional SendGrid Services

SendGrid offers several APIs and webhooks that you can use to leverage additional functionality within your Azure application. For more details, see the SendGrid API Reference.

Next steps

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