In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and C#.
(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.
- Sign up for a SendGrid account.
- Enable Two-factor authentication.
- Create and store a SendGrid API Key with Mail Send > Full Access permissions.
- Complete Domain Authentication.
- 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, you'll be able to send 100 emails per day forever. For more account options, see our pricing 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 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.
Install C#
install-c page anchor
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.
C# version check
c-version-check page anchor
Check your C# version by opening your terminal (also known as a command line or console) and typing the following command.
_10 dotnet --version
Initialize your project
initialize-your-project page anchor
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.
(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.
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:
_10 dotnet add package SendGrid _10 _10 //use Twilio SendGrid wiith HttpClientFactory _10 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 and the .NET 4.5.2 Example 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
.
Complete code block
complete-code-block page anchor
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 _25 using System; _25 using System.Threading.Tasks; _25 using SendGrid; _25 using SendGrid.Helpers.Mail; _25 _25 class 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 }
Build your API call
build-your-api-call page anchor
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
orPUT
, 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.
_10 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.
_10 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.
_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.
_10 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
.
_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
.
_10 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:
_10 var 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 }; _10 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.
_10 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.
_18 using System; _18 using System.Threading.Tasks; _18 using SendGrid; _18 _18 class 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.
Troubleshooting
troubleshooting page anchor
If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.
API Response messages
api-response-messages page anchor
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.
Additional Resources
additional-resources page anchor
- "How to Send Email with C# and Twilio SendGrid" video
- "Receive an SMS and email it using Twilio SendGrid, C# and .NET Core"(link takes you to an external page) blog post by Layla Porter
(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.
Next Steps
next-steps page anchor
This is just the beginning of what you can do with our APIs. To learn more, check the resources below.
- API Reference
- Sending Email with Dynamic Transactional Templates
- Getting Started with the Event Webhook
- The Email Activity Feed
- Sender Authentication
- Twilio SendGrid helper library for C#