Send Attachments with Amazon-SES

Yots picture Yots · Jul 19, 2011 · Viewed 16.5k times · Source

I'm searching for an working C# example to send attachments with Amazon-SES.

After reading that Amazon-SES now supports sending attachments I was searching for an C# example but was unable to find one.

Answer

KKKas picture KKKas · Jan 7, 2016

I think that using AWS SDK for .NET and MimeKit is very easy and clean solution. You can send e-mails with attachments via SES API (instead of SMTP).

You can write MimeMessage directly to MemoryStream and then use it with SES SendRawEmail:

using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using Amazon;
using Amazon.Runtime;
using MimeKit;

private static BodyBuilder GetMessageBody()
{
    var body = new BodyBuilder()
    {
        HtmlBody = @"<p>Amazon SES Test body</p>",
        TextBody = "Amazon SES Test body",
    };
    body.Attachments.Add(@"c:\attachment.txt");
    return body;
}

private static MimeMessage GetMessage()
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("Foo Bar", "[email protected]"));
    message.To.Add(new MailboxAddress(string.Empty, "[email protected]"));
    message.Subject = "Amazon SES Test";
    message.Body = GetMessageBody().ToMessageBody();
    return message;
}

private static MemoryStream GetMessageStream()
{
    var stream = new MemoryStream();
    GetMessage().WriteTo(stream);
    return stream;
}

private void SendEmails()
{
    var credentals = new BasicAWSCredentials("<aws-access-key>", "<aws-secret-key>");

    using (var client = new AmazonSimpleEmailServiceClient(credentals, RegionEndpoint.EUWest1))
    {
        var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage(GetMessageStream()) };
        try
        {
            var response = client.SendRawEmail(sendRequest);
            Console.WriteLine("The email was sent successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The email was not sent.");
            Console.WriteLine("Error message: " + e.Message);
        }
    }
}