转换MailMessage原始文本 [英] Convert MailMessage to Raw text

查看:143
本文介绍了转换MailMessage原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法来一个System.Net.Mail.MailMessage对象转换为原始邮件文本,当您在记事本中打开一个EML文件等。

Is there any easy way to convert a System.Net.Mail.MailMessage object to the raw mail message text, like when you open a eml file in notepad.

推荐答案

下面是同样的解决方案,但作为一个扩展的方法来 MailMessage

Here's the same solution, but as an extension method to MailMessage.

部分的反射开销是由静态背景下抓住了 ConstructorInfo 的MethodInfo 成员一旦最小化。

Some of the reflection overhead is minimized by grabbing the ConstructorInfo and MethodInfo members once in the static context.

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

要抓住根本的MemoryStream

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

这篇关于转换MailMessage原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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