Home > Amazon Web Servces (AWS), Uncategorized > Use Amazon Simple Email Service (Amazon SES) in .NET

Use Amazon Simple Email Service (Amazon SES) in .NET

September 12, 2011 Leave a comment Go to comments

Amazon Simple Email Service (Amazon SES) is a highly scalable and cost-effective bulk and transactional email-sending service for businesses and developers. You will get the details here in http://aws.amazon.com/ses/

Here is the basic functionality available in Amazon SES service as described in http://aws.amazon.com/ses/

Amazon SES lets you send bulk and transactional email to customers in a quick and cost-effective manner. To use Amazon SES you simply:

Sign Up: After signing up, you can access the Amazon SES sandbox – an environment specifically designed for developers to test and evaluate the service.

• Verify Email Addresses: Before you can send email via Amazon SES, you need to verify that you own the email address from which you’ll be sending email. To verify an email address, make an API call with the email address as a parameter. This API call will trigger a verification email, which will contain a link that you can click on to complete the verification process.

• Request Production Access: Once you are ready to use Amazon SES to send email, you request production access. This will allow you to move from the sandbox environment to the production environment and begin sending email to your customers. It only takes a few minutes to apply for production access, and you usually receive a response within 24 hours.

• Send Email: Amazon SES has two different APIs for queuing an email message for delivery. The first allows you to specify the components of a message for an SMTP-compliant email message; the second enables you to send a raw message, and specify your own email headers and MIME types.

• Get Feedback: Amazon SES provides useful statistics about your sending activities. With a simple query, you can quickly obtain vital statistics such as volume sent, bounces and complaints.

Here I will describe how can we use it from .net application with an example.

AWS SDK for .NET

The AWS .NET SDK is a single, downloadable package that includes Visual Studio project templates, the AWS .NET library, C# code samples, and documentation.
You can download AWS SDK for .NET from here http://aws.amazon.com/sdkfornet/

Getting Your AWS Security Credentials

In order to use the AWS SDK for .NET, you will need your AWS security credentials, which AWS assigned you when you created your AWS account. The security credentials used with the AWS SDK for .NET is a pair of public/private keys:
• Access Key ID (For example: 022QF06E7MXBSH9DHM02)
• Secret Access Key (For example: kWcrlUX5JEDGM/LtmEENI/aVmYvHNif5zB+d9+ct)
You can view your security creadentials from here after signup http://aws.amazon.com/security-credentials.

Use the AWS SDK from .NET

So now we can start our example to use Amazon SES service from .Net application.
So create a c# console application and add a reference to the AWSSDK (AWS SDK for .NET).
I didn’t create a separate project to write the AWS service instead I have added a class AmazonSESService.cs where we will define the methods to access amazon SES services. I have taken a lot of help from here http://amazonses.codeplex.com/ for this example.

We will use some entity classes for our example in Entity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AWS_SES.Entities
{
    /// <summary>
    /// Holds the sended email info.
    /// </summary>
    public class SentEmailResult
    {
        public Exception ErrorException { get; set; }
        public string MessageId { get; set; }
        public bool HasError { get; set; }

        public SentEmailResult()
        {
            this.HasError = false;
            this.ErrorException = null;
            this.MessageId = string.Empty;
        }
    }

    /// <summary>
    /// Send Quota Response 
    /// </summary>
    public class SendQuota
    {
        public double Max24HourSend { get; set; }
        public double MaxSendRate { get; set; }
        public double SentLast24Hours { get; set; }
    }

    public class Email
    {
        public List<string> ToAddresseList { get; set; }
        public List<string> CCAddresseList { get; set; }
        public List<string> BCCAdressList { get; set; }
        public string SenderEmailAddress { get; set; }
        public string ReplyToEmailAddress { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public string Text { get; set; }
    }
}

Bellow in the following class methods are written to verify and send email using Amazon SES service.

namespace AWS_SES
{
    public class AmazonSESService
    {
        private AmazonSimpleEmailServiceClient client;

        private AmazonSESService()
        {
        }

        public AmazonSESService(string accessKey, string secretKey)
        {
            AccessKey = accessKey;
            SecretKey = secretKey;
            client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(accessKey, secretKey);
        }

        public string AccessKey { get; set; }
        public string SecretKey { get; set; }

        /// <summary>
        /// Send Email with specified email object
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public SentEmailResult SendEmail(Email email)
        {
            return SendEmail(email.ToAddresseList, email.CCAddresseList, email.BCCAdressList, email.SenderEmailAddress,
                email.ReplyToEmailAddress, email.Subject, email.Body);
        }

        /// <summary>
        /// Send Email Via Amazon SES
        /// </summary>
        /// <param name="awsAccessKey"></param>
        /// <param name="awsSecretKey"></param>
        /// <param name="to">List of strings TO address collection</param>
        /// <param name="cc">List of strings CCC address collection</param>
        /// <param name="bcc">List of strings BCC address collection</param>
        /// <param name="senderEmailAddress">Sender email. Must be verified before sending.</param>
        /// <param name="replyToEmailAddress">Reply to email.</param>
        /// <param name="subject">Mail Subject</param>
        /// <param name="body">Mail Body</param>
        /// <returns></returns>
        private SentEmailResult SendEmail(List<string> to, List<string> cc, List<string> bcc, string senderEmailAddress, string replyToEmailAddress, string subject, string body)
        {
            SentEmailResult result = new SentEmailResult();

            try
            {
                List<string> listColTo = new List<string>();
                listColTo.AddRange(to);

                Destination destinationObj = new Destination();
                destinationObj.ToAddresses.AddRange(listColTo);

                if (cc != null)
                {
                    List<string> listColCc = new List<string>();
                    listColCc.AddRange(cc);
                    destinationObj.BccAddresses.AddRange(listColCc);
                }

                if (bcc != null)
                {
                    List<string> listColBcc = new List<string>();
                    listColBcc.AddRange(bcc);
                    destinationObj.CcAddresses.AddRange(listColBcc);
                }

                SendEmailRequest mailObj = new SendEmailRequest();
                mailObj.Destination = destinationObj;
                mailObj.Source = senderEmailAddress;
                mailObj.ReturnPath = replyToEmailAddress;

                ////Create Message
                Content emailSubjectObj = new Content(subject);
                Content emailBodyContentObj = new Content(body);

                //Create email body object
                Body emailBodyObj = new Body();
                emailBodyObj.Html = emailBodyContentObj;
                emailBodyObj.Text = emailBodyContentObj;

                //Create message
                Message emailMessageObj = new Message(emailSubjectObj, emailBodyObj);
                mailObj.Message = emailMessageObj;

                //Send Message
                SendEmailResponse response = client.SendEmail(mailObj);
                result.MessageId = response.SendEmailResult.MessageId;
            }
            catch (Exception ex)
            {
                //If any error occurs, HasError flag will be set to true.
                result.HasError = true;
                result.ErrorException = ex;
            }

            return result;
        }


        /// <summary>
        /// Send a verification email to specified email. Amazon SES needs to a verified email in order to use it as a sender email.
        /// When this function calls, a verification email will be sent to specified email. You need to click the verification link on the upcoming email.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool VerifyEmailAddress(string email)
        {
            bool result = false;

            VerifyEmailAddressRequest request = new VerifyEmailAddressRequest();
            VerifyEmailAddressResponse response = new VerifyEmailAddressResponse();

            if (client != null)
            {

                request.EmailAddress = email.Trim();
                response = client.VerifyEmailAddress(request);

                if (!string.IsNullOrEmpty(response.ResponseMetadata.RequestId))
                {
                    result = true;
                }
            }

            return result;
        }
}
}

Prior to sending email you must have to verify the email address you want to send email. You can do this by using the function VerifyEmailAddress.

Bellow is the function to use the AmazonSESService SendEmail and VerifyEmailAddress methods.

private static void VerifyEmailAddress()
        {
            Console.WriteLine("Enter Email Address to Verify:");
            Console.ReadLine();
            string emailAddress = Console.ReadLine();

            try
            {
                bool verified = amazonSESService.VerifyEmailAddress(emailAddress);

                if (verified)
                {
                    Console.WriteLine("Email Address successfully verified");
                }
                else
                {
                    Console.WriteLine("An email has been sent for verification.");
                    Console.WriteLine("Click link in email to verify");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error");
            }

        }

        private static void SendEmail()
        {
            Console.WriteLine("Enter Email Address to Send Email");
            Console.ReadLine();
            string emailAddress = Console.ReadLine();

            try
            {
                Email email = new Email
                {
                    SenderEmailAddress = "test@youremail.com",
                    ToAddresseList = new List<string> { emailAddress },
                    Subject = "test",
                    Body = "Test Email"
                };

                amazonSESService.SendEmail(email);
                Console.WriteLine("Email successfully sent");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending Email");
            }
        }

Get the llist of verified email address list

        /// <summary>
        /// Lists the verified sender emails 
        /// </summary>
        /// 
        public List ListVerifiedEmailAddresses()
        {
            //client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(secretKey, secretKey);
            ListVerifiedEmailAddressesRequest request = new ListVerifiedEmailAddressesRequest();
            ListVerifiedEmailAddressesResponse response = new ListVerifiedEmailAddressesResponse();

            List verifiedEmailList = new List();
            response = client.ListVerifiedEmailAddresses(request);
            if (client != null)
            {
                if (response.ListVerifiedEmailAddressesResult != null)
                {
                    if (response.ListVerifiedEmailAddressesResult.VerifiedEmailAddresses != null)
                    {
                        verifiedEmailList.AddRange(response.ListVerifiedEmailAddressesResult.VerifiedEmailAddresses);
                    }
                }
            }

            return verifiedEmailList;
        }

Get Send Qouta information from Amazon

/// <summary>
        /// Get Send Qouta information from Amazon
        /// </summary>
        /// 
        public SendQuota GetSendQuotaInformation()
        {
            SendQuota sendQuota = new SendQuota();
            GetSendQuotaRequest request = new GetSendQuotaRequest();
            GetSendQuotaResponse response = new GetSendQuotaResponse();

            if (client != null)
            {
                response = client.GetSendQuota(request);

                if (!string.IsNullOrEmpty(response.ResponseMetadata.RequestId))
                {
                    if (response.GetSendQuotaResult != null)
                    {
                        sendQuota.Max24HourSend = response.GetSendQuotaResult.Max24HourSend;

                        sendQuota.MaxSendRate = response.GetSendQuotaResult.MaxSendRate;

                        sendQuota.SentLast24Hours = response.GetSendQuotaResult.SentLast24Hours;
                    }
                }
            }

            return sendQuota;
        }
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: