gpt4 book ai didi

amazon-ses - NET中将MailMessage转换为MemoryStream

转载 作者:行者123 更新时间:2023-12-01 06:00:55 31 4
gpt4 key购买 nike

我正在将.Net Core 1.2与Amazon SES(SimpleEmail)一起使用来发送电子邮件(原始电子邮件)。

以下是我们在.net Framework 4.5中使用的工作代码版本:

   public 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, 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;

}


但是在.Net Core 1.2中,我们无法获取SmtpClient和System.Net.Mail.MailWriter的类Assembly的引用。下面是在常规.net框架中工作的方法:

Assembly assembly = typeof(SmtpClient).Assembly;


在.Net Core中,由于Mailkit中提供了SmtpClient,因此我们已对其进行引用并给出以下错误:

'Type' does not contain a definition for 'Assembly' and no extension method 'Assembly' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)


.Net Core中有什么方法可以将MailMessage转换为MemoryStream?

最佳答案

** 试试这个**

 private static string ConvertMailMessageToMemoryStream(MailMessage message)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
MemoryStream stream = new MemoryStream();
ConstructorInfo mailWriterConstructor = mailWriterType.GetConstructor(flags, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterConstructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", flags);
sendMethod.Invoke(message, flags, null, new[] { mailWriter, true, true }, null);
var sr = new StreamReader(stream);
var str = sr.ReadToEnd();
MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", flags);
closeMethod.Invoke(mailWriter, flags, null, new object[] { }, null);
return str;
}

关于amazon-ses - NET中将MailMessage转换为MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498161/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com