Skip to contentSkip to navigationSkip to topbar
On this page

Email API Quickstart for C#


In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and C#(link takes you to an external page).

(information)

Info

These are C# installation prerequisites:

  • .NET Framework 4.0+ (only available on Windows)
  • .NET Core 1.0+
  • .NET Standard 1.3+

Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API Key with Mail Send > Full Access permissions.
  4. Complete Domain Authentication.
  5. Install C#.

Sign up for a SendGrid account

sign-up-for-a-sendgrid-account page anchor

When you sign up for a free SendGrid account(link takes you to an external page), you'll be able to send 100 emails per day forever. For more account options, see our pricing page(link takes you to an external page).


Enable Two-factor authentication

enable-two-factor-authentication page anchor

Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy(link takes you to an external page) app. See the 2FA section of our authentication documentation for instructions.


Create and store a SendGrid API key

create-and-store-a-sendgrid-api-key page anchor

Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.

Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.


Verify your Sender Identity

verify-your-sender-identity page anchor

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.

(information)

Info

To get started quickly, you may be able to skip Domain Authentication and begin by completing Single Sender Verification. Single Sender Verification is recommended for testing only. Some email providers have DMARC policies that restrict email from being delivered using their domains. For the best experience, please complete Domain Authentication. Domain Authentication is also required to upgrade from a free account.


If you do not already have a version of C# installed, visit the .Net Framework website(link takes you to an external page) to download and install a version appropriate for your operating system.


Check your C# version by opening your terminal (also known as a command line or console) and typing the following command.

dotnet --version

Using a Twilio SendGrid helper library(link takes you to an external page) is the fastest way to deliver your first email.

Start by creating a project folder for this app. You can name the project anything you like.

(information)

Info

If you do not have a version of NuGet installed, you can download and install it using the NuGet installation instructions on docs.microsoft.com(link takes you to an external page).


Install the helper library

install-the-helper-library page anchor

To use Twilio SendGrid in your C# project, you can either download the Twilio SendGrid C# .NET libraries directly from our Github repository or if you have the NuGet package manager installed, you can grab them automatically:

1
dotnet add package SendGrid
2
3
//use Twilio SendGrid wiith HttpClientFactory
4
dotnet add package SendGrid.Extensions.DependencyInjection

Once you have the Twilio SendGrid library installed, you can start making calls to SendGrid in your code. For sample implementations, see the .NET Core Example(link takes you to an external page) and the .NET 4.5.2 Example(link takes you to an external page) folders.


How to Send an Email with the SendGrid API

how-to-send-an-email-with-the-sendgrid-api page anchor

You're now ready to write some code. First, create a file in your project directory. You can use Program.cs.


The following C# block contains all the code needed to successfully deliver a message with the SendGrid Mail Send API. You can copy this code, modify the from_email and to_email variables, and run the code if you like. We'll break down each piece of this code in the following sections.

1
/*
2
* Hello Email
3
* The following is the minimum needed code to send a simple email. Use this exam* ple, and modify the apiKey, from and to variables:
4
*/
5
6
using System;
7
using System.Threading.Tasks;
8
using SendGrid;
9
using SendGrid.Helpers.Mail;
10
11
class Program
12
{
13
static async Task Main()
14
{
15
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
16
var client = new SendGridClient(apiKey);
17
var from_email = new EmailAddress("test@example.com", "Example User");
18
var subject = "Sending with Twilio SendGrid is Fun";
19
var to_email = new EmailAddress("test@example.com", "Example User");
20
var plainTextContent = "and easy to do anywhere, even with C#";
21
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
22
var msg = MailHelper.CreateSingleEmail(from_email, to_email, subject, plainTextContent, htmlContent);
23
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
24
}
25
}
26

Your API call must have the following components:

  • A host (the host for Web API v3 requests is always https://api.sendgrid.com/v3/ )
  • An API key passed in an Authorization Header
  • A request (when submitting data to a resource via POST or PUT , you must submit your request body in JSON format)

In your Program.cs file, import the SendGrid helper library. The library will handle setting the Host, https://api.sendgrid.com/v3/, for you.

using Sendgrid;

Next, use the API key you set up earlier. Remember, the API key is stored in an environment variable, so you can use the Environment.GetEnvironmentVariable(<name>) method to access it. This means we also need to import the System namespace.

using System;

Assign the key to a variable named apiKey. Using the helper library's SendGridClient() method, pass your key to the v3 API in an Authorization header using Bearer token authentication.

1
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
2
var client = new SendGridClient(apiKey);

Now you're ready to set up the from_email, to_email, subject, and message body content. These values are passed to the API in a "personalizations"(link takes you to an external page) object when using the v3 Mail Send API. You can assign each of these values to variables, and the SendGrid library will handle creating a personalizations object for you.

First, import the Sendgrid.Helpers.Mail namespace.

using Sendgrid.Helpers.Mail;

With the helpers imported, define and assign values for from_email, to_email, subject, and content variables. Assigning an email address like from_email = new EmailAddress("test@example.com","Test User" will construct an EmailAddress object using the provided email and name arguments respectively. Be sure to assign the to_email to an address with an inbox you can access.

You have two options for the content type: text/plain or text/html.

1
var from_email = new EmailAddress("test@example.com", "Example User");
2
var subject = "Sending with Twilio SendGrid is Fun";
3
var to_email = new EmailAddress("test@example.com", "Example User");
4
var plainTextContent = "and easy to do anywhere, even with C#";
5
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong";

To properly construct the message, pass each of the previous variables into the SendGrid Helper library's CreateSingleEmail method's parameters which returns a SendGridMessage object. You can assign this to a variable named msg.

var msg = MailHelper.CreateSingleEmail(from_email, to_email, subject, plainTextContent, htmlContent);

For more advanced use cases, you can build the SendGridMessage object yourself with these minimum required settings:

1
var msg = new SendGridMessage()
2
{
3
From = new EmailAddress("from@example.com", "Golden Dawn"),
4
Subject = "Sending With Twilio SendGrid is Fun",
5
PlainTextContent = "and easy to do anywhere, even with C#",
6
HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>"
7
};
8
msg.AddTo(new EmailAddress("to@example.com", "To User"));

Lastly, you need to make a request to the SendGrid Mail Send API to deliver your message.

var response = await client.SendEmailAsync(msg).ConfigureAwait(false);

The helper library uses SendGrid's csharp-http-client(link takes you to an external page) library to construct the request URL by chaining together portions of your desired path.

The path to the SendGrid v3 Mail Send endpoint is https://api.sendgrid.com/v3/mail/send. The SendGrid helper library has set the client for you, so the base https://api.sendgrid.com/v3 is taken care of when we make a call to the SendGridClient objects RequestAsync method.

With the baseUrl built, we must pass the arguments method, requestBody, queryParams, urlPath, and cancellationToken, to the RequestAsync method with all being optional except the method parameter. To submit a GET request you can use the SendGridClient.Method.GET. The requestBody and queryParams must be provided JSON formatted values.

1
using System;
2
using System.Threading.Tasks;
3
using SendGrid;
4
5
class Program
6
{
7
static async Task Main()
8
{
9
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
10
var client = new SendGridClient(apiKey);
11
var queryParams = @"{'limit': 100}";
12
var response = await client.RequestAsync(
13
method: SendGridClient.Method.GET,
14
urlPath: "supression/bounce",
15
queryParams: queryParams)
16
.ConfigureAwait(false);
17
}
18
}
19

With all this code in place, you can run your Program.cs file with C# to send the email.

If you receive a 202 status code(link takes you to an external page) printed to the console, your message was sent successfully. Check the inbox of the “to_email” address, and you should see your demo message.

If you don't see the email, you may need to check your spam folder.


If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.


All responses are returned in JSON format. We specify this by sending the Content-Type header. The Web API v3 provides a selection of response codes, content-type headers, and pagination options to help you interpret the responses to your API requests.


(information)

Info

Get additional onboarding support. Save time, increase the quality of your sending, and feel confident you are set up for long-term success with SendGrid Onboarding Services(link takes you to an external page).


This is just the beginning of what you can do with our APIs. To learn more, check the resources below.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.