using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Amazon.SimpleEmail.Model;
using Amazon.SimpleEmail;
using System.Net.Mail;
using Postal;
using System.IO;
namespace Postal.Extensions
{
public class MailExtensions
{
///
/// Take a dynamic Postal generated view and send it via Amazon SES
///
/// Dynamic Postal View
public static void SendEmailBySES(dynamic email)
{
try
{
//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);
}
catch (Exception ex)
{
//TODO: Record exception
}
}
///
/// Convert a MailMessage object to an Amazon SES SendEmailRequest object
///
///
///
public static SendEmailRequest ConvertFromMailMessage(MailMessage msg)
{
SendEmailRequest mailObj = new SendEmailRequest();
Destination destination = new Destination();
//Set From address
mailObj.Source = msg.From.Address;
//Check for ReplyTo address and take first one
if (msg.ReplyToList.Count > 0)
{
mailObj.ReturnPath = msg.ReplyToList[0].Address;
}
//Add all To address
foreach (MailAddress addy in msg.To)
{
destination.ToAddresses.Add(addy.Address);
}
//Add all CC address
foreach (MailAddress addy in msg.CC)
{
destination.CcAddresses.Add(addy.Address);
}
//Add all BCC address
foreach (MailAddress addy in msg.Bcc)
{
destination.BccAddresses.Add(addy.Address);
}
//Set the desination object
mailObj.Destination = destination;
Content emailSubjectObj = new Content(msg.Subject);
Body emailBodyObj = new Body();
if (msg.AlternateViews.Count > 0)
{
//Add text view
using (StreamReader reader = new StreamReader(msg.AlternateViews[0].ContentStream))
{
emailBodyObj.Text = new Content(reader.ReadToEnd());
}
//Add HTML view
using (StreamReader reader = new StreamReader(msg.AlternateViews[1].ContentStream))
{
emailBodyObj.Html = new Content(reader.ReadToEnd());
}
}
else if (!string.IsNullOrEmpty(msg.Body))
{
emailBodyObj.Html = new Content(msg.Body);
}
Message emailMessageObj = new Message(emailSubjectObj, emailBodyObj);
mailObj.Message = emailMessageObj;
return mailObj;
}
}
}