Amazon SES Integration with .NET

Mine Kaya
BosphorusISS
Published in
8 min readOct 20, 2023

Hi, in this post you will learn what is Amazon SES and how to use and integrate it with .NET for verifying email addresses, sending emails, creating templates, and sending templated emails. I wrote this post because I couldn’t find any good, up-to-date resources that covered all of these topics in one place. I hope this will be a simple and helpful guide for you to get started. Enjoy!

What is Amazon SES?

Amazon Simple Email Service (Amazon SES) is a cloud-based email sending service that provides cost-effective, flexible and scalable way to send emails using your own domain and email addresses.

There are several use cases for using SES like transactional or marketing emails also it is really efficient with bulk email communication if you reach out large communities.

Pros and Cons of Amazon SES — Why to Use It?

Pros:

  • high deliverability and reliability along with high sending rates
  • no need for maintenance once setup is done
  • you can not only send emails but also retrieve them with SES (its recuries a bit more configuration)

Cons:

  • A complicated initial configuration. Of course documentation has lots of sections and it’s very easy to get lost while trying to start from beginning (well, you are welcome)
  • There limitations before Amazon verifies your domain. You need to correctly configure Amazon SES and for expanding your limits you have to open a case and submit a request for it.
  • Maybe you will not need it, but I found building a template and sending them a bit confusing. (you are welcome again)

Before we start you might want to take a look at to official documentation. For Amazon SES, you will find the documantation here.

This post will assume that you already have an AWS Account. If you are totally new to AWS, you need to create an AWS account first.

Let’s Dive In to SES

On your AWS management console, search for SES and go to its dashboard and click the button says create identity. I will not change anything and go with the default configuration now.

Once you create your identity, you will be redirected to verified identities page , and select your domain and go its page. You will see there are info boxes that says you have to verify your domain. Yeah, it’s a bit annoying, but it’s a matter of security that I mentioned before. You need to verify all email identities you use. You can follow this AWS guide for it.

As you can see on your domain’s identity board verification process may take up to 72 hours.

After you got the verification, there are two ways to set up email sending with Amazon SES. First one is sending emails through SMTP, other one is sending them via SES API. I will mention both of them but continue to develop with API.

If you’re not planing to do something too complicated I suggest that go with SMTP, because first of all its just basic SMTP, so it easier. And as you can see here, it says only advantage of API is the option of using HTTP connections for increase throughput. This is not available for the SMTP option.

But please note that, for my case I needed to send templated emails too. And if you go to SES Dashboard and click the Email templates section, you will see the info box that says :

So for creating a template and sending an email with it we have to use the API.

But before we start working with the API, I want to give you a simple SMTP example too.

1. Using SMTP

Amazon SES SMTP endpoint requires delivery over authenticated encrypted connections. Amazon SES supports two ways to establish TLS-encrypted connection: STARTTLS and TLS Wrapper. You can see them here.

First we need to get our SMTP credentials from AWS. Go to your SES Dashboard and on the left menu click the SMTP settings and create your SMTP credentials. After you will have one SMTP Username and SMTP Password within it.

Please note that, until your domain moves from sandbox, you can only send mail to a verified email addresses. You can add your an email address like adding your domain, just choose the email. After you create your email identity, Amazon will send you a verification mail and after you verify your address its ready to send or recieve emails through SES. I will show you how to do it with API in the next section.

Amazon SES SMTP endpoint requires delivery over authenticated encrypted connections. Amazon SES supports two wayto establishing TLS-encrypted connection:  STARTTLS and TLS Wrapper. You can see here.

2. Using SES API

Amazon SES API lets us to send email when we give the content of the email. It assembles a MIME email for you. Also you can assemble the email yourself too. By doing that you will have complete control over the content of the message.

MIME (Multipurpose Internet Mail Extensions) is an extension of the original SMTP. It lets users exchange different kinds of data files, including audio, video, images, over email.

For documentation go to Amazon Simple Email Service API.

You can use this API in three diffrent ways:

  • Make direct HTTPS requests to API
  • With using AWS SDK
  • With using AWS CLI

Whichever that you choose to access, Amazon SES API provides two different ways to send an email, depends to how much control you want.

  • Formatted — With formatted email, you only supply “From:” and “To:” addresses, a subject, and a message body. Amazon SES takes care of all the rest. You can send mail withSendEmail operation, with giving to info about from_address, to address, subject, body (body can be :text, HTML, or both)
  • Raw — You manually compose and send an email message, specifying your own email headers and MIME types. You can use the Amazon SES SendRawEmail operation to send highly customized messages to your recipients.

I will continue with the formatted mail. But if you want to go forward with raw, go here.

Send Mail with SES API

I will reach the API through AWS SDK. For doing that first we need an AWS access key ID and AWS secret key to access Amazon SES. You can find your credentials by using the Security Credentials page.

First create your MailService and constructor invoke to AmazonSimpleEmailServiceClient with your credentials and specified with region that you are on.


private readonly AmazonSimpleEmailServiceClient _amazonSimpleEmailServiceClient;

public EmailService()
{
_amazonSimpleEmailServiceClient = new AmazonSimpleEmailServiceClient(_sesConfiguration.AccessKey, _sesConfiguration.SecretKey, region: RegionEndpoint.EUNorth1);
}

And lets create a method that sends mail with using our client. By using the API we can create our endpoint to send a mail withSendEmailAsync

   public async Task<string> SendEmailAsync(List<string> toAddresses, string bodyHtml, string bodyText, string subject)
{
var messageId = "";
try
{
var response = await _amazonSimpleEmailServiceClient.SendEmailAsync(
new SendEmailRequest
{
Destination = new Destination
{
ToAddresses = toAddresses
},
Message = new Message
{
Body = new Body
{
Html = new Content
{
Charset = "UTF-8",
Data = bodyHtml
},
Text = new Content
{
Charset = "UTF-8",
Data = bodyText
}
},
Subject = new Content
{
Charset = "UTF-8",
Data = subject
}
},
Source = _sesConfiguration.SourceEmail
});

messageId = response.MessageId;

}
catch (Exception ex)
{
throw ex;
}

return messageId;
}

Send Verification Mail with SES API

With using the API we can create our endpoint to send a verification email to email addresses withVerifyEmailIdentityAsync. This will help us to add an email reciepient to SES.

You will not need to add user like that when you complete your verification process for your identity as I mentioned. After you move out from sandbox you can send it to every email address.

 public async Task<bool> VerifyEmailIdentityAsync(string mail)
{
var success = false;
try
{
var response = _amazonSimpleEmailServiceClient.VerifyEmailIdentityAsync(
new VerifyEmailIdentityRequest
{
EmailAddress = mail
}).Result;

success = response.HttpStatusCode == HttpStatusCode.OK;

}
catch (Exception ex)
{
throw ex;
}

return success;
}

The email address that you want to verify will get an email from no-reply-aws@amazon.com same as the ones with you create on SES Dashboard. By clicking the link email will be verified and you can send emails to this account until your identity is verified.

Create Template With SES API

You can use CreateTemplateAsync to create your custom templates, you will find them later with TemplateName that you will give on create request.

 public async Task<bool> CreateEmailTemplateAsync(string name, string subject, string text, string html)
{
var success = false;
try
{
var response = await _amazonSimpleEmailServiceClient.CreateTemplateAsync(
new CreateTemplateRequest
{
Template = new Template
{
TemplateName = name,
SubjectPart = subject,
TextPart =text,
HtmlPart = html
}
});
success = response.HttpStatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
throw ex;
}

return success;
}

Lets check our template on SES Dashboard and go to Email Templates page.

For example if you want to use dynamic user name in the mail, you can send your html part like that when creating a template

    "<h3>Welcome</h3>" +
" <p> Dear: {{userName}} <br>" + //username
" Thank you for creating a account! <br>" +
" </p>";

Let’s send an email with this template and see how we can change the userName

Sending Templated Mail With SES API

Besides SendEmailAsync now we will use SendTemplatedEmailAsync

  public async Task<string> SendTemplatedEmailAsync(string toAddress, string userName)
{
var messageId = "";
try
{
var response = await _amazonSimpleEmailServiceClient.SendTemplatedEmailAsync(
new SendTemplatedEmailRequest
{
Source = _sesConfiguration.SourceEmail,
Destination = new Destination
{
ToAddresses = new List<string> { toAddress }
},
Template = _templateHelper.GetTemplateName((int)TemplateEnum.WELCOME),
TemplateData = $"{{ \"userName\":\"{userName}\" }}"
});
messageId = response.MessageId;

}
catch (Exception ex)
{
throw ex;
}

return messageId;
}

I create helper for getting template names easily, but you can use name of it too, but I assumed hard-coded usage could be cause some syntax error along the way, you can consider this too create a structure for that.

Thank you for reading, hope it helped you !

Docs that may help :

--

--