Using ASP.NET MVC Views to Send Email via Amazon Simple Email Service using Postal

At the MvcConf 2 Andrew Davey (@andrewdavey) presented a neat emailing utility for ASP.NET MVC 3 called Postal that allows for using View Engines to ease the creation of email templates, and also takes care of sending the emails out.  During the session someone raised the question about sending through third-party services, namely Amazon Simple Email Service.  Since Postal relies on .NET's SmtpMail, there wasn't a straight forward solution.  This following post is about a hack I built to get around this... until something better crops up.  It's certainly not the most efficient way, but it does work.

What You'll Need

Postal - lets you create emails using regular MVC views.  Use NuGet to get the package and get started instantly.

Amazon Simple Email Service -  a highly scalable and cost-effective bulk and transactional email-sending service for businesses and developers.  Download and install the Amazon SDK and reference the DLL in your project.

Here's what I hacked together for now which I just called MailExtensions:

SendEmailBySES - Handles everything from the dynamic Postal view to sending the message via Amazon SES.

public static void SendEmailBySES(dynamic email) {  
    //Create Amazon SES client instance
    AmazonSimpleEmailServiceClient client 
        = new AmazonSimpleEmailServiceClient("accessKey", "secretKey");
    //create postal service instance

    IEmailService service = new EmailService(ViewEngines.Engines);
    //create the mail message
    MailMessage msg = service.CreateMailMessage(email);
    //convert MailMessage object to Amazon SES SendEmailRequest object
    SendEmailRequest mailObj = ConvertFromMailMessage(msg);
    //Send the email via SES
    dynamic response = client.SendEmail(mailObj);
}

ConvertFromMailMessage - Converts a MailMessage object to an Amazon SES SendEmailRequest object.

The code for this is a bit longer and more hacky so just download it instead.  You can *download the source here.*

NOTE: If you aren't setup with Amazon SES you'll have to signup up, and then need to verify your email addresses initially and go through the sandbox.  Then you'll have to apply for production.  Below is a snippet to verify your email address through the API:

public static void VeryifySESEmail(string addy)  
{
    VerifyEmailAddressRequest verRequest = new VerifyEmailAddressRequest();
    verRequest.EmailAddress = addy;
    VerifyEmailAddressResponse verResponse = client.VerifyEmailAddress(verRequest); 
}