将MailMessage转换为原始文本

Cra*_*aig 13 .net c#

有没有简单的方法将System.Net.Mail.MailMessage对象转换为原始邮件消息文本,就像在记事本中打开eml文件一样.

all*_*aya 19

这是相同的解决方案,但作为一种扩展方法MailMessage.

通过在静态上下文中抓取ConstructorInfoMethodInfo成员一次,可以最大限度地减少一些反射开销.

/// <summary>
/// Uses reflection to get the raw content out of a MailMessage.
/// </summary>
public static class MailMessageExtensions
{
    private static readonly BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
    private static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
    private static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(Stream) }, null);
    private static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags);
    private static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", Flags);

    /// <summary>
    /// A little hack to determine the number of parameters that we
    /// need to pass to the SaveMethod.
    /// </summary>
    private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;

    /// <summary>
    /// The raw contents of this MailMessage as a MemoryStream.
    /// </summary>
    /// <param name="self">The caller.</param>
    /// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
    public static MemoryStream RawMessage(this MailMessage self)
    {
        var result = new MemoryStream();
        var mailWriter = MailWriterConstructor.Invoke(new object[] { result });
        SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);
        result = new MemoryStream(result.ToArray());
        CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null);
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

抓住底层MemoryStream:

var email = new MailMessage();
using (var m = email.RawMessage()) {
    // do something with the raw message
}
Run Code Online (Sandbox Code Playgroud)

  • 这是否适用于PC上的.NET 4.5中的"发送"附加参数?我必须在调用`CloseMethod`之前将`result`的内容复制到另一个`MemoryStream`,因为当前的实现实际上将关闭底层流. (2认同)

jst*_*ast 8

我在MimeKit中实现了逻辑,允许您将System.Net.Mail.MailMessage 强制转换为MimeKit.MimeMessage.完成后,您只需将消息写入流:

var message = (MimeMessage) CreateSystemNetMailMessage ();
using (var stream = File.Create ("C:\\message.eml"))
    message.WriteTo (stream);
Run Code Online (Sandbox Code Playgroud)

这不需要反映到内部方法中,这意味着它不依赖于运行时,使其比目前为止给出的其他答案更具可移植性.