Rahul Patel
Rahul Patel

Reputation: 500

Create MIME Mail with attachment for AWS SES c#

I am trying to send an AWS SES mail with attachment using SDK. I found working code here:

it refers MimeKitLite but this we can not refer in .net framework 3.5. Is there any workaround I can write in my code to send the mail using framework 3.5? due to some dependencies we cannot upgrade our project framework.

I am writing here my working code (framework 4) for reference:

    protected void Page_Load(object sender, EventArgs e)
        {
            var message = (MimeMessage)MyMailMessage();
            var stream = new MemoryStream();
            message.WriteTo(stream);
            using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient("awsAccessKeyId", "awsSecretAccessKey", RegionEndpoint.USWest2))
            {
                var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
                var response = client.SendRawEmail(sendRequest);
                Console.WriteLine(response.ToString());
            }
        }

   private static MimeKit.MimeMessage MyMailMessage()
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("rahul", "[email protected]"));
            message.To.Add(new MailboxAddress("rahul", "[email protected]"));
            message.Subject = "Hello";
            var builder = new BodyBuilder();
            builder.HtmlBody = @"<p>Thank you for submitting your query/complaint.";
            //
            string attachement = System.Web.HttpContext.Current.Server.MapPath(Path.GetFileName("IntelOCL.log"));
            builder.LinkedResources.Add(attachement);
            message.Body = builder.ToMessageBody();
            return message;
        }

Upvotes: 0

Views: 3877

Answers (1)

JPG
JPG

Reputation: 545

You can use the .NET MailMessage class instead. The problem with this is that you have to give Amazon SES the raw content of the message in a stream and this class does not have a direct way to do that (afaik). It can be done however by using reflection:

private MemoryStream FromMailMessageToMemoryStream(MailMessage message)
{
   Assembly assembly = typeof(SmtpClient).Assembly;

   Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

   MemoryStream stream = new MemoryStream();

   ConstructorInfo mailWriterContructor = 
      mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
        object mailWriter = mailWriterContructor.Invoke(new object[] { stream });

   MethodInfo sendMethod = 
      typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);

   if (sendMethod.GetParameters().Length == 3)
   {
      sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null); // .NET 4.x
   }
   else
   {
      sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null); // .NET < 4.0 
   }

   MethodInfo closeMethod = 
      mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
   closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);

    return stream;
}

With this helper function your code would be now:

protected void Page_Load(object sender, EventArgs e)
    {
        var message = (MailMessage)MyMailMessage();
        var stream = FromMailMessageToMemoryStream(message);
        List<string> bccTo = new List<string>();
        bccTo.Add("[email protected]");
        using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient("awsAccessKeyId", "awsSecretAccessKey", RegionEndpoint.USWest2))
        {
            var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
            var response = client.SendRawEmail(sendRequest);
            Console.WriteLine(response.MessageId);

            if (bccTo != null && bccTo.Count > 0)
            {
                sendRequest.Destinations = bccTo;
                response = client.SendRawEmail(sendRequest);
                Console.WriteLine(response.MessageId);
            }
        }
    }

private static MailMessage MyMailMessage()
    {
        var message = new MailMessage();
        message.From = new MailAddress("[email protected]", "rahul");
        message.To.Add("[email protected]");
        message.Subject = "Hello";
        message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(@"<p>Thank you for submitting your query/complaint.", new ContentType("text/html")));
        //
        string attachmentname = "IntelOCL.log";
        Stream ms = new MemoryStream(File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath(Path.GetFileName(attachmentname))));
        ContentType ct = new ContentType();
        ct.MediaType = "" // TODO
        Attachment attachment = new Attachment(ms, ct);
        attachment.Name = attachmentname;
        attachment.ContentDisposition.FileName = attachmentname;
        message.Attachments.Add(attachment);

        return message;
    }

Upvotes: 5

Related Questions