c# - 将 MailMessage 转换为原始文本

标签 c# .net

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

最佳答案

这是相同的解决方案,但作为 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;
    }
}

获取底层MemoryStream:

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

关于c# - 将 MailMessage 转换为原始文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7515457/

相关文章:

c# - TabControl 中 ImageList 图标的分辨率不清晰

c# - 将 byte[] 转换为字符串

.net - 这有可能将 "If Then Else"折叠为方法吗?

c# - 调用 native (DllImport) 函数时出现 StackOverflowException

c# - IUnityContainer.CreateChildContainer() 抛出 NullReferenceException

c# - 将 TextBox.Text 绑定(bind)到 DataSet.DataSetName

c# - 设置窗口位置

c# - Linq GroupBy 子句不包括计数为零的项目

c# - 如何将 SRP 应用于用户界面类?

c# - 为什么 Generic Casting 不适用于这部分代码?