How to send email in C# using SendGrid and SOLID design principles

Post author: Adam VanBuskirk
Adam VanBuskirk
5/14/23 in
Tech
C#

Here is example code for sending an email using the SendGrid API in C# using SOLID design principles. First, let’s define the required models for the email message:

public class EmailAddress
{
    public string Email { get; set; }
    public string Name { get; set; }
}

public class EmailMessage
{
    public List<EmailAddress> ToAddresses { get; set; }
    public List<EmailAddress> CcAddresses { get; set; }
    public List<EmailAddress> BccAddresses { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}

These models define the basic information for sending an email, such as the recipient email addresses, the subject and the body of the email.

Next, we’ll create an interface for the email service, which defines the contract for sending emails:

public interface IEmailService
{
    void SendEmail(EmailMessage emailMessage);
}

This interface will be implemented by the concrete class that sends the email. Next, let’s create the concrete implementation of the email service using SendGrid. The SendGridClient class is part of the SendGrid package, so you will need to install the SendGrid NuGet package to use it.

To install the SendGrid NuGet package in your C# project, you can follow these steps:

  1. Open your project in Visual Studio.
  2. Right-click on the project in the Solution Explorer and select “Manage NuGet Packages”.
  3. In the “Browse” tab, search for “SendGrid” and select the “SendGrid” package from the search results.
  4. Click the “Install” button to install the package in your project.

After installing the package, you can add the following using statement at the top of your C# file to use the SendGrid classes.

using SendGrid;

public class SendGridEmailService : IEmailService
{
    private readonly string _apiKey;

    public SendGridEmailService(string apiKey)
    {
        _apiKey = apiKey;
    }

    public void SendEmail(EmailMessage emailMessage)
    {
        var client = new SendGridClient(_apiKey);
        var msg = new SendGridMessage();

        msg.SetFrom(new EmailAddress("noreply@example.com", "Example Company"));

        foreach (var to in emailMessage.ToAddresses)
        {
            msg.AddTo(new EmailAddress(to.Email, to.Name));
        }

        if (emailMessage.CcAddresses != null)
        {
            foreach (var cc in emailMessage.CcAddresses)
            {
                msg.AddCc(new EmailAddress(cc.Email, cc.Name));
            }
        }

        if (emailMessage.BccAddresses != null)
        {
            foreach (var bcc in emailMessage.BccAddresses)
            {
                msg.AddBcc(new EmailAddress(bcc.Email, bcc.Name));
            }
        }

        msg.SetSubject(emailMessage.Subject);
        msg.AddContent(MimeType.Html, emailMessage.Body);

        client.SendEmailAsync(msg).Wait();
    }
}

This class implements the IEmailService interface and uses the SendGrid API to send emails. It takes the SendGrid API key as a parameter in its constructor. Finally, here’s an example of how to use the SendGridEmailService class to send an email:

var emailService = new SendGridEmailService("YOUR_SENDGRID_API_KEY");

var emailMessage = new EmailMessage
{
    ToAddresses = new List<EmailAddress> {
        new EmailAddress { Email = "recipient@example.com", Name = "Recipient Name" }
    },
    CcAddresses = new List<EmailAddress> {
        new EmailAddress { Email = "cc@example.com", Name = "CC Name" }
    },
    BccAddresses = new List<EmailAddress> {
        new EmailAddress { Email = "bcc@example.com", Name = "BCC Name" }
    },
    Subject = "Test email",
    Body = "<html><body><h1>Test email</h1><p>This is a test email.</p></body></html>"
};

emailService.SendEmail(emailMessage);

How it Works

We defined two models for the email message, an interface for the email service, a concrete class for sending emails using SendGrid, and an example of how to use the SendGridEmailService class to send an email. The design follows the SOLID principles, where each class has a single responsibility and is easily maintainable and testable.

The EmailMessage class has a single responsibility of representing the email message and its properties, and the IEmailService interface defines the contract for sending emails, which can be implemented by any email service. The SendGridEmailService class implements the IEmailService interface and has the responsibility of using the SendGrid API to send emails.

The implementation of the SendEmail method in the SendGridEmailService class follows the Single Responsibility principle, where the method has a single responsibility of sending the email using the SendGrid API. The code uses the SendGrid client to create a message and set its properties, such as the sender, recipient, subject, and body, and then sends the email asynchronously.

Finally, the example usage of the SendGridEmailService class shows how easy it is to use the email service by creating an EmailMessage object and passing it to the SendEmail method of the email service. This code follows the Open-Closed principle, where the SendGridEmailService class can be extended or modified to support additional email providers without changing the usage of the class by the clients.

In conclusion, this example code demonstrates how to send emails using SendGrid API in C# while following the SOLID principles, which makes the code easy to maintain and test.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC