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.
_10dotnet --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:
_10dotnet add package SendGrid_10_10//use Twilio SendGrid wiith HttpClientFactory_10dotnet 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.
_25/*_25* Hello Email_25* The following is the minimum needed code to send a simple email. Use this exam* ple, and modify the apiKey, from and to variables:_25*/_25_25using System;_25using System.Threading.Tasks;_25using SendGrid;_25using SendGrid.Helpers.Mail;_25_25class Program_25{_25 static async Task Main()_25 {_25 var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");_25 var client = new SendGridClient(apiKey);_25 var from_email = new EmailAddress("test@example.com", "Example User");_25 var subject = "Sending with Twilio SendGrid is Fun";_25 var to_email = new EmailAddress("test@example.com", "Example User");_25 var plainTextContent = "and easy to do anywhere, even with C#";_25 var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";_25 var msg = MailHelper.CreateSingleEmail(from_email, to_email, subject, plainTextContent, htmlContent);_25 var response = await client.SendEmailAsync(msg).ConfigureAwait(false);_25 }_25}
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.
_10using 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.
_10using 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.
_10 var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");_10 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" 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.
_10using 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
.
_10 var from_email = new EmailAddress("test@example.com", "Example User");_10 var subject = "Sending with Twilio SendGrid is Fun";_10 var to_email = new EmailAddress("test@example.com", "Example User");_10 var plainTextContent = "and easy to do anywhere, even with C#";_10 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
.
_10var 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:
_10var msg = new SendGridMessage()_10{_10 From = new EmailAddress("from@example.com", "Golden Dawn"),_10 Subject = "Sending With Twilio SendGrid is Fun",_10 PlainTextContent = "and easy to do anywhere, even with C#",_10 HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>"_10};_10msg.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.
_10var 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.
_18using System;_18using System.Threading.Tasks;_18using SendGrid;_18_18class Program_18{_18 static async Task Main()_18 {_18 var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");_18 var client = new SendGridClient(apiKey);_18 var queryParams = @"{'limit': 100}";_18 var response = await client.RequestAsync(_18 method: SendGridClient.Method.GET,_18 urlPath: "supression/bounce",_18 queryParams: queryParams)_18 .ConfigureAwait(false);_18 }_18}
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.