Send Email with Aattachment, on AWS SES in C#/.Net using Amazon.SimpleEmailV2

0

I'm sending simple emails and templated emails, now I need to add attachment, but I tried everything that I found and anything worked, someone can help? or send a simple code how to send an email with attachment in AWS SES v2 with C#/.Net

2 Answers
0
Accepted Answer

To attach a file to an email with Amazon SES, you must use SendRawEmail as follows.
https://docs.aws.amazon.com/ja_jp/ses/latest/dg/send-email-raw.html

NET, you should be able to use SendRawEmailRequest as described in the following document.
https://docs.aws.amazon.com/sdkfornet/latest/apidocs/items/TSimpleEmailSendRawEmailRequestNET45.html

profile picture
EXPERT
answered 10 months ago
0

There doesn't appear to be great support, if any support, to send emails with attachments in SES in the traditional MailMessage way using Smtp classes within .net.

This is for .net 8. It likely works for .net 6 and above.

The easiest way to send emails with attachments will be to add MimeKit to your project. The following code worked within a lambda function as well. I've verified the following works, the AWS documentation directs you to raw email sending but lacks examples using attachments if you were to piece together a raw email yourself.

 var client = new AmazonSimpleEmailServiceV2Client(RegionEndpoint.USEast1)
    var mime = new MimeMessage();

    var bodyBuilder = new BodyBuilder();
    mime.From.Add(new MailboxAddress("email", username));
    mime.To.Add(new MailboxAddress("email", sendTo));

    mime.Subject = $"Email Subject With Date - {DateTime.UtcNow:yyyyMMdd}";

    // attachments here would be a List of a custom class of attachments that looks like
    // public class MyAttachment
    // {
    //     public Byte[] File { get; set; }
    //     public string FileName { get; set; }
    // }
    // var attachments = new List<MyAttachment>();
    // attachments.Add(new MyAttachment { FileName = "MyFileName.csv", File = <read in a file and convert to bytes> });'

    foreach (var item in attachments)
    {
        bodyBuilder.Attachments.Add(item.FileName, item.File, ContentType.Parse("text/csv"));
    }

    mime.Body = bodyBuilder.ToMessageBody();

    var stream = new MemoryStream();
    mime.WriteTo(stream);

    var request = new SendEmailRequest();
    request.Content = new EmailContent();
    request.Content.Raw = new RawMessage();
    request.Content.Raw.Data = stream;

    await client.SendEmailAsync(request);

Adjust text/csv, csv file information to meet needs of whatever it is you are attaching. I believe there is a 10MB attachment limit when sending emails with SES.

profile picture
answered 2 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions