In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and C#.
These are C# installation prerequisites:
Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.
When you sign up for a free SendGrid account, you'll be able to send 100 emails per day forever. For more account options, see our pricing page.
Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy app. See the 2FA section of our authentication documentation for instructions.
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.
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.
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 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 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.
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.
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:
1dotnet add package SendGrid23//use Twilio SendGrid wiith HttpClientFactory4dotnet 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 and the .NET 4.5.2 Example folders.
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 Email3* 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*/56using System;7using System.Threading.Tasks;8using SendGrid;9using SendGrid.Helpers.Mail;1011class Program12{13static async Task Main()14{15var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");16var client = new SendGridClient(apiKey);17var from_email = new EmailAddress("test@example.com", "Example User");18var subject = "Sending with Twilio SendGrid is Fun";19var to_email = new EmailAddress("test@example.com", "Example User");20var plainTextContent = "and easy to do anywhere, even with C#";21var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";22var msg = MailHelper.CreateSingleEmail(from_email, to_email, subject, plainTextContent, htmlContent);23var response = await client.SendEmailAsync(msg).ConfigureAwait(false);24}25}26
Your API call must have the following components:
https://api.sendgrid.com/v3/
)
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.
1var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");2var 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" 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
.
1var from_email = new EmailAddress("test@example.com", "Example User");2var subject = "Sending with Twilio SendGrid is Fun";3var to_email = new EmailAddress("test@example.com", "Example User");4var plainTextContent = "and easy to do anywhere, even with C#";5var 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:
1var msg = new SendGridMessage()2{3From = new EmailAddress("from@example.com", "Golden Dawn"),4Subject = "Sending With Twilio SendGrid is Fun",5PlainTextContent = "and easy to do anywhere, even with C#",6HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>"7};8msg.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 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.
1using System;2using System.Threading.Tasks;3using SendGrid;45class Program6{7static async Task Main()8{9var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");10var client = new SendGridClient(apiKey);11var queryParams = @"{'limit': 100}";12var response = await client.RequestAsync(13method: SendGridClient.Method.GET,14urlPath: "supression/bounce",15queryParams: 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
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.
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.
This is just the beginning of what you can do with our APIs. To learn more, check the resources below.