Amazon have just released a beta of a new service called Amazon Simple Email Service (SES) that allows you to send out emails with saleability. I’m not here to discuss the service itself, so you can read more information about it here. You can also view more information about the APIs here and sign-up for it here.

Whilst the service is in beta, you can only send emails to the email addresses that you have verified (I’ll discuss how this is done later!) unless you request production access from Amazon.

Note: I created a AWS Console project in Visual Studio which is available to me because I have the AWSSDK.NET installed. During creation this asks for you AWS Keys and places them in the app.config file and is referenced in my code via AppConfig[ ] and

private static readonly NameValueCollection AppConfig = ConfigurationManager.AppSettings;

Listing Verified Email Address

This method will return a String List (List) of each email address that has been verified with Amazon. I’m showing this method first as I use it later when verifying email addresses to prevent re-verifying an already verified email address.

public static void ListVerifiedEmailAddresses()
{
	List<String> verifiedEmailAddresses = GetVerifiedEmailAddresses();

	if (verifiedEmailAddresses.Count > 0)
	{
		Console.WriteLine("Verfied email addresses: \n");

		foreach (String verifiedEmailAddress in verifiedEmailAddresses)
		{
			Console.WriteLine("\t" + verifiedEmailAddress);
		}
	}
	else
	{
		Console.WriteLine("No email addresses have been verified.");
	}

	Console.WriteLine();
}

public static List<String> GetVerifiedEmailAddresses()
{
	AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);

	ListVerifiedEmailAddressesRequest request = new ListVerifiedEmailAddressesRequest();

	try
	{
		ListVerifiedEmailAddressesResponse response = ses.ListVerifiedEmailAddresses(request);

		ListVerifiedEmailAddressesResult result = response.ListVerifiedEmailAddressesResult;

		List<String> verifiedEmailAddresses = result.VerifiedEmailAddresses;

		return verifiedEmailAddresses;
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);

		return new List<String>();
	}
}

The first method above, ListVerifiedEmailAddresses(), is just to output the results, if any, line by line to the console. The main work is done by the second method, GetVerifiedEmailAddresses() which returns the String List of verified email addresses.

 

Lines 24 to 26 create my client connection to SES fetching my AWS Keys from the app.config file as mentioned in my note above.

Lines 28/29 create a new ListVerifiedEmailAddressRequest request that we will use when talking to the SES service.

Lines 33/34 passes the request to the SES service and gets the response from the service as a ListVerifiedEmailAddressResponse. This response contains the result that we then get to via lines 36/37 and 39/40 before returning the String List.

These last few lines could be compacted down, but I have left them in this form to show how it all relates together and for tidier code on this blog.

Verify Email Address

Before you can send an email through SES, you must verify the email address the service will send the email from. When you talk to the service to verify an email address it will send an email to the address with a link that the recipient uses to verify the email address. Until this is done, the email address will not show in the Verified Email Address list the code above retrieves.

My method below includes some console output which I won’t discuss in detail.

public static Boolean VerifyEmailAddress(String emailAddress)
{
	List<String> verifiedEmailAddresses = GetVerifiedEmailAddresses();

	if (!verifiedEmailAddresses.Contains(emailAddress))
	{
		AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);

		VerifyEmailAddressRequest request = new VerifyEmailAddressRequest();

		request.WithEmailAddress(emailAddress);

		try
		{
			VerifyEmailAddressResponse response
			= ses.VerifyEmailAddress(request);

			Console.WriteLine("An email has been sent for verification.");
			Console.WriteLine("Click link in email to verify");
			Console.WriteLine();
			Console.WriteLine(String.Format("Request ID: {0}", response.ResponseMetadata.RequestId));

			return true;
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);

			return false;
		}
	}

	Console.WriteLine("Email address already verified.");

   return true;
}

As I mentioned earlier, I use the GetVerifiedEmailAddresses() method that I discussed in the previous section of this blog to get a list of currently verified email addresses (Lines 3/4). On line 6 I then check to see if the list contains the email address I am trying to verify now. If it does, we don’t need to re-verify it. I haven’t done any checks for case-sensitive email addresses, but I’m sure you could easily add this!

 

If it’s not in the list of verified email addresses, then I get a connection to the SES service again with lines 8-10. Lines 12-15 build my request to verify an email address. Line 15 being where we actually specify the email address we are verifying in the request.

Lines 19/20 then communicate with the SES service and get back a response. This response only contains a Request ID. If this was successful then an email will have been sent to the email address specified with a link to verify the email address with Amazon.

If the email address was already in the list then we output a relevant message to the console and return from the method.

Once you have clicked this link and the email address has been verified with Amazon, then the address will appear in the List Verified Email Address methods above.

Sending Email

Now that we have a verified email address, we can start to use the service. As I mentioned above, unless you request otherwise, Amazon will only allow you to send emails to the verified email addresses.

public static Boolean SendEmail(String From, String To, String Subject, String Text = null, String HTML = null, String emailReplyTo = null, String returnPath = null)
{
	if (Text != null && HTML != null)
	{
		String from = From;

		List<String> to
			= To
			.Replace(", ", ",")
			.Split(',')
			.ToList();

		Destination destination = new Destination();
		destination.WithToAddresses(to);
		//destination.WithCcAddresses(cc);
		//destination.WithBccAddresses(bcc);

		Content subject = new Content();
		subject.WithCharset("UTF-8");
		subject.WithData(Subject);

		Content html = new Content();
		html.WithCharset("UTF-8");
		html.WithData(HTML);

		Content text = new Content();
		text.WithCharset("UTF-8");
		text.WithData(Text);

		Body body = new Body();
		body.WithHtml(html);
		body.WithText(text);

		Message message = new Message();
		message.WithBody(body);
		message.WithSubject(subject);

		AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);

		SendEmailRequest request = new SendEmailRequest();
		request.WithDestination(destination);
		request.WithMessage(message);
		request.WithSource(from);

		if (emailReplyTo != null)
		{
			List<String> replyto
				= emailReplyTo
				.Replace(", ", ",")
				.Split(',')
				.ToList();

			request.WithReplyToAddresses(replyto);
		}

		if (returnPath != null)
		{
			request.WithReturnPath(returnPath);
		}

		try
		{
			SendEmailResponse response = ses.SendEmail(request);

			SendEmailResult result = response.SendEmailResult;

			Console.WriteLine("Email sent.");
			Console.WriteLine(String.Format("Message ID: {0}",
				result.MessageId));

			return true;
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);

			return false;
		}
	}

	Console.WriteLine("Specify Text and/or HTML for the email body!");

	return false;
}

This method is the longest of the lot. Mainly because of the way that the email request is constructed. This method along with the others contains sloppy coding, but is just for example purposes so I’ll let this pass Winking smile

 

I’ve included some default values in my method some of which are not required to send an email. HTML & Text are required, but at least only one of them is. This is why I gave them defaults so I can check if either has been specified and give back an error message if they aren’t. This is done on lines 5/6.

For To and ReplyTo I use a input type of String, but in my method I convert them to String Lists separating the email address with at the ‘;’ character. So a list of emails to send to would be passed to the method like “email@domain.com; email2@domain2.co.uk” etc. This is done on lines 9-13 and 48-52.

First we create a Destination giving it the To addresses on lines 15/16. You can also include any CC or BCC addresss here. I have commented out the code on lines 17/18 where this can be done as I am not using them in the example.

Now we need to create Content for the email itself. We create a Content for Subject (lines 20-22), and the two body types (Text and HTML – lines 24-26 and 28-30) specifying a Character Set of UTF-8 for each. We then create a Body and pass in the Text and/or HTML (both in my example) on lines 32-34.

Then we create a Message which we give our Body and subject Content to on lines 36-38.

Now we have constructed out Destination and Message we can communicate with the service to get the email sent.

As before we connect to the service with lines 40-42 and then create a SendEmailRequest request that we provide with our Destination, Message and out From email address, which is all done on lines 44-47.

If we have provided the optional ReplyTo email address (where replies to the email will be delivered) and the ReturnPath email address (where bounce backs will arrive) we also add these to our service request.

We then pass this request to the service and get back its response on line 67.

From this response we get the result (line 69) which contains a Message ID which we output to the console on lines 71-73 along with an email sent message.

If you check your email you should see it has been delivered!

In my next post I will go through examples of:

  • Deleting Verified Email Addresses
  • Sending Raw Email

Hope this helps people starting to look at this service. If demand is there I can supply the project code. Let me know in comments below!

Neil

UPDATE: Something I forgot to mention during my original post was that the ReplyTo and ReturnPath email addresses need to be verified also.

UPDATE 2: The latest AWS SDK for .NET seems to depricate the method I used to connect to AWS. Change it to:

 

AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(awsAccessKeyId, awsSecretAccessKey);