为 AWS SES c# 创建带有附件的 MIME 邮件

Create MIME Mail with attachment for AWS SES c#

我正在尝试使用 SDK 发送带有附件的 AWS SES 邮件。我找到了工作代码 here

它指的是MimeKitLite,但是我们不能在.net Framework 3.5 中引用它。我可以在我的代码中编写任何解决方法来使用框架 3.5 发送邮件吗? 由于某些依赖关系,我们无法升级我们的项目框架。

我在这里写下我的工作代码(框架4)以供参考:

    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", "rpatel.alld@Gmail.com"));
            message.To.Add(new MailboxAddress("rahul", "rpatel.alld@Gmail.com"));
            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;
        }

您可以改用 .NET MailMessage class。这样做的问题是您必须在流中向 Amazon SES 提供消息的原始内容,而此 class 没有直接的方法来做到这一点 (afaik)。但是可以通过使用反射来完成:

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;
}

有了这个辅助函数,您的代码现在应该是:

protected void Page_Load(object sender, EventArgs e)
    {
        var message = (MailMessage)MyMailMessage();
        var stream = FromMailMessageToMemoryStream(message);
        List<string> bccTo = new List<string>();
        bccTo.Add("chris@domain.com");
        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("rpatel.alld@Gmail.com", "rahul");
        message.To.Add("rpatel.alld@Gmail.com");
        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;
    }