How To Send Email Using Sendgrid C#

Sending emails through your application is a crucial aspect in various situations. A popular platform for performing this task is SendGrid. In this guide, we will discuss the process of sending emails using SendGrid in C#.

Prerequisites

Before we get started, ensure you have the following:

  • A SendGrid account. If you don’t have one, you can sign up for a free account here.
  • SendGrid API key. This can be obtained from your SendGrid dashboard.
  • .NET Core SDK installed on your machine.

Setting Up Your Project

Create a new C# console application in your preferred IDE (Visual Studio, JetBrains Rider, etc.).

Installing SendGrid NuGet Package

You’ll need to install the SendGrid NuGet package. You can do this by running the following command in the package manager console:

Install-Package SendGrid -Version 9.22.0

Creating the SendEmail Function

Now, let’s create a function that will handle sending the email. Name this function SendEmail.

public async Task SendEmail(string ToEmail, string subject, string content)
{
    var apiKey = "<your sendgrid api key>";
    var client = new SendGridClient(apiKey);
    var from = new EmailAddress("[email protected]", "Example User");
    var to = new EmailAddress(ToEmail, "Example User");
    var msg = MailHelper.CreateSingleEmail(from, to, subject, content, content);
    var response = await client.SendEmailAsync(msg);
}

In the above function, replace “<your SendGrid API key>” with your actual SendGrid API key. The function accepts the recipient’s email, the subject, and the content of the email as parameters. It creates a new SendGrid client with your API key, constructs the email, and sends it out.

Calling the SendEmail Function

Now let’s call the function from the Main function of our console application:

static void Main(string[] args)
{
    SendEmail("[email protected]", "Hello from SendGrid", "This is a test email.").GetAwaiter().GetResult();
}

You should replace [email protected] with the actual recipient’s email. When you run the application, it will send the email and wait until it finishes before it exits.

Conclusion

With SendGrid and C#, sending emails from your application is a breeze. This tutorial has provided you with a basic understanding of how to integrate SendGrid with a C# application. For more advanced features like sending emails to multiple recipients, attachments, etc., refer to the official SendGrid documentation.