Tuesday, February 22, 2011

Amazon Web Services Simple Email Service - Send a message using System.Net.Mail.MailMessage

This is an example of converting a System.Net.Mail.MailMessage for use with Amazon Web Services Simple Email Service.

var message = new System.Net.Mail.MailMessage("me@nowhere.com", "somewhere@nowhere.com", "test message", "this is the body of the message");
var credentials = new System.Net.NetworkCredential("UserName", "Password");

var client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient(credentials.UserName, credentials.Password);

var request = new Amazon.SimpleEmail.Model.SendEmailRequest()
.WithSource(message.From.Address) //The from email address
.WithReturnPath(message.ReplyToList == null || message.ReplyToList.Count <= 0 ? message.From.Address : message.ReplyToList[0].Address) //The email address for bounces
.WithDestination(new Amazon.SimpleEmail.Model.Destination(message.To.Select(a => a.Address).ToList()));

request = request.WithMessage(message.IsBodyHtml ?
new Amazon.SimpleEmail.Model.Message()
.WithBody(new Amazon.SimpleEmail.Model.Body()
.WithHtml(new Amazon.SimpleEmail.Model.Content(message.Body)))
.WithSubject(new Amazon.SimpleEmail.Model.Content(message.Subject))
:
new Amazon.SimpleEmail.Model.Message()
.WithBody(new Amazon.SimpleEmail.Model.Body()
.WithText(new Amazon.SimpleEmail.Model.Content(message.Body)))
.WithSubject(new Amazon.SimpleEmail.Model.Content(message.Subject))
);

client.SendEmail(request);

No comments: