使用AWS SES c#的附件创建MIME邮件 [英] Create MIME Mail with attachment for AWS SES c#

查看:168
本文介绍了使用AWS SES c#的附件创建MIME邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SDK发送带附件的AWS SES邮件。我发现工作代码此处

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

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

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.

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

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", "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 。这样做的问题是,您必须将Amazon SES的消息的原始内容发送到流中,并且此类没有直接的方法(afaik)。可以通过使用反射来实现:

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

这篇关于使用AWS SES c#的附件创建MIME邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆