将邮件转换为 .net core 中的 MemoryStream



我正在使用 .Net Core 1.2 和 Amazon SES(SimpleEmail( 来发送电子邮件(Raw Email(。

下面是我们在 .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 中,由于 SmtpClient 在 MailKit 中可用,因此我们引用了它并给出了以下错误:

'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吗?

看起来在dotnet core 5.0中没有构造函数只接受一个参数,试试这个。

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

** 试试这个**

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

相关内容

  • 没有找到相关文章

最新更新