Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Attachments with Amazon-SES

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.

like image 354
Yots Avatar asked Jul 19 '11 06:07

Yots


People also ask

How do I send an attachment through Amazon SES?

File attachments To attach a file to an email, you have to encode the attachment using base64 encoding. Attachments are typically placed in dedicated MIME message parts, which include the following headers: Content-Type: The file type of the attachment.

Can SES send attachments?

You can send messages with attachments through Amazon SES by using the Multipurpose Internet Mail Extensions (MIME) standard. Amazon SES accepts all file attachment types except for attachments with the file extensions in the following list.

Can I use AWS SES to send email?

With Amazon SES, you can send an email in three ways: using the console, using the Simple Mail Transfer Protocol (SMTP) interface, or using the API.

Can SNS send attachment?

No, it can't. The SNS FAQ does not come out and explain this explicitly, but it can be inferred from several statements: Amazon SNS messages can contain up to 256 KB of text data, including XML, JSON and unformatted text.


2 Answers

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);         }     } } 
like image 93
KKKas Avatar answered Sep 24 '22 10:09

KKKas


public Boolean SendRawEmail(String from, String to, String cc, String Subject, String text, String html, String replyTo, string attachPath)     {         AlternateView plainView = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, "text/plain");         AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, "text/html");          MailMessage mailMessage = new MailMessage();          mailMessage.From = new MailAddress(from);          List<String> toAddresses = to.Replace(", ", ",").Split(',').ToList();          foreach (String toAddress in toAddresses)         {             mailMessage.To.Add(new MailAddress(toAddress));         }          List<String> ccAddresses = cc.Replace(", ", ",").Split(',').Where(y => y != "").ToList();          foreach (String ccAddress in ccAddresses)         {             mailMessage.CC.Add(new MailAddress(ccAddress));         }          mailMessage.Subject = Subject;         mailMessage.SubjectEncoding = Encoding.UTF8;          if (replyTo != null)         {             mailMessage.ReplyToList.Add(new MailAddress(replyTo));         }          if (text != null)         {             mailMessage.AlternateViews.Add(plainView);         }          if (html != null)         {             mailMessage.AlternateViews.Add(htmlView);         }          if (attachPath.Trim() != "")         {             if (System.IO.File.Exists(attachPath))             {                 System.Net.Mail.Attachment objAttach = new System.Net.Mail.Attachment(attachPath);                 objAttach.ContentType = new ContentType("application/octet-stream");                  System.Net.Mime.ContentDisposition disposition = objAttach.ContentDisposition;                 disposition.DispositionType = "attachment";                 disposition.CreationDate = System.IO.File.GetCreationTime(attachPath);                 disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachPath);                 disposition.ReadDate = System.IO.File.GetLastAccessTime(attachPath);                 mailMessage.Attachments.Add(objAttach);             }         }          RawMessage rawMessage = new RawMessage();          using (MemoryStream memoryStream = ConvertMailMessageToMemoryStream(mailMessage))         {             rawMessage.WithData(memoryStream);         }          SendRawEmailRequest request = new SendRawEmailRequest();         request.WithRawMessage(rawMessage);          request.WithDestinations(toAddresses);         request.WithSource(from);          AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(ConfigurationManager.AppSettings.Get("AccessKeyId"), ConfigurationManager.AppSettings.Get("SecretKeyId"));          try         {             SendRawEmailResponse response = ses.SendRawEmail(request);             SendRawEmailResult result = response.SendRawEmailResult;             return true;         }         catch (AmazonSimpleEmailServiceException ex)         {             return false;         }     }     public static MemoryStream ConvertMailMessageToMemoryStream(MailMessage message)     {         Assembly assembly = typeof(SmtpClient).Assembly;         Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");         MemoryStream fileStream = new MemoryStream();         ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);         object mailWriter = mailWriterContructor.Invoke(new object[] { fileStream });         MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);         sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null);         MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);         closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);         return fileStream;     } 

Found that here

Update: A method signature has changed in .NET 4.5, which breaks the above: Getting System.Net.Mail.MailMessage as a MemoryStream in .NET 4.5 beta

like image 33
Erick Smith Avatar answered Sep 25 '22 10:09

Erick Smith