How to Send Email Using SendGrid with Azure


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 or SendGrid's C# library GitHub repo.

Create a SendGrid Account

To sign up for a SendGrid account

  1. Sign in to the Azure portal.

  2. In the Azure portal menu or the home page, select Create a resource.

    Screenshot of the Azure portal menu with the Create a resource option selected.

  3. Search for and select SendGrid.

    Screenshot of the Azure portal Marketplace screen showing "SendGr" in the search box and SendGrid selected in the search results.

  4. Complete the signup form and select Create.

    Screenshot of the Create a New SendGrid Account dialog with the Name, Password, Subscription and Resource group fields filled in.

  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.

    Screenshot of the Create a New SendGrid Account dialog with the Choose your pricing tier section opened

  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.

    Screenshot of the SendGrid Accounts page showing the new account ContosoSendGrid listed.

    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 our FAQ.

    Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

    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.

    Screenshot showing that the Settings page for the ContosoSendGrid account is opened by selecting All settings from the ContosoSendGrid account page.

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

To find your SendGrid API Key

  1. Click Manage.

    Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

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

    Screenshot of the SendGrid dashboard with the Settings dropdown opened and API Keys selected.

  3. Click the Create API Key.

    Screenshot of the API Keys screen with the Create API Key button selected.

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

    Screenshot of the Add New General API Key screen with Mail Send set to Full Access, Scheduled Sends set to No Access, and the Save button highlighted.

  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.

    Screenshot of the ContosoSendGrid account page with the Key icon highlighted.

  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.

Screenshot of the ContosoSendGrid account page with the Manage button highlighted.

For more information on sending email through SendGrid, visit the 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.


To install NuGet if you are running a version of Visual Studio earlier than Visual Studio 2015, visit, 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("", "SendGrid DX Team"));

var recipients = new List<EmailAddress>
    new EmailAddress("", "Jeff Smith"),
    new EmailAddress("", "Anna Lidman"),
    new EmailAddress("", "Peter Saddow")

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 an email message using the SendGrid Web API with a console application.

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

namespace Example
    internal class Example
        private static void Main()

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

How to: Send email from ASP .NET Core API using MailHelper class

The below example can be used to send a single email to multiple persons from the ASP .NET Core API using the MailHelper class of SendGrid.Helpers.Mail namespace. For this example we are using ASP .NET Core 1.0.

In this example, the API key has been stored in the appsettings.json file which can be overridden from the Azure portal as shown in the above examples.

The contents of appsettings.json file should look similar to:

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"

First, we need to add the below code in the Startup.cs file of the .NET Core API project. This is required so that we can access the SENDGRID_API_KEY from the appsettings.json file by using dependency injection in the API controller. The IConfiguration interface can be injected at the constructor of the controller after adding it in the ConfigureServices method below. The content of Startup.cs file looks like the following after adding the required code:

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
        // Add mvc here

At the controller, after injecting the IConfiguration interface, we can use the CreateSingleEmailToMultipleRecipients method of the MailHelper class to send a single email to multiple recipients. The method accepts one additional boolean parameter named showAllRecipients. This parameter can be used to control whether email recipients will be able to see each others email address in the To section of email header. The sample code for controller should be like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SendGrid;
using SendGrid.Helpers.Mail;
using Microsoft.Extensions.Configuration;

namespace SendgridMailApp.Controllers
    public class NotificationController : Controller
       private readonly IConfiguration _configuration;

       public NotificationController(IConfiguration configuration)
         _configuration = configuration;

       public async Task PostMessage()
          var apiKey = _configuration.GetSection("SENDGRID_API_KEY").Value;
          var client = new SendGridClient(apiKey);
          var from = new EmailAddress("", "Example User 1");
          List<EmailAddress> tos = new List<EmailAddress>
              new EmailAddress("", "Example User 2"),
              new EmailAddress("", "Example User 3"),
              new EmailAddress("","Example User 4")

          var subject = "Hello world email from Sendgrid ";
          var htmlContent = "<strong>Hello world with HTML content</strong>";
          var displayRecipients = false; // set this to true if you want recipients to see each others mail id 
          var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false);
          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"

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:

        "Some Footer HTML",
        "<strong>Some Footer Text</strong>");

Click tracking


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.