如何将 MailMessage 对象保存到磁盘作为 *.eml 或 *.msg 文件

发布于 2024-08-02 10:23:36 字数 114 浏览 4 评论 0原文

如何将 MailMessage 对象保存到磁盘? MailMessage 对象不公开任何 Save() 方法。

如果它以任何格式保存,*.eml 或 *.msg,我都没有问题。知道如何做到这一点吗?

How do I save MailMessage object to the disk? The MailMessage object does not expose any Save() methods.

I dont have a problem if it saves in any format, *.eml or *.msg. Any idea how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

爱你不解释 2024-08-09 10:23:36

为简单起见,我将仅引用 连接项

您实际上可以配置
SmtpClient 将电子邮件发送到文件
系统而不是网络。你可以
使用以下方式以编程方式执行此操作
以下代码:

SmtpClient 客户端 = new SmtpClient("mysmtphost");
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = @"C:\somedirectory";
客户端.发送(消息);

您也可以在您的
应用程序配置文件如
这个:

 <configuration>
     <system.net>
         <mailSettings>
             <smtp deliveryMethod="SpecifiedPickupDirectory">
                 <specifiedPickupDirectory pickupDirectoryLocation="C:\somedirectory" />
             </smtp>
         </mailSettings>
     </system.net>
 </configuration>

发送电子邮件后,您应该
查看电子邮件文件已添加到
您指定的目录。那么你可以
有一个单独的进程发送
批处理模式下的电子邮件。

您应该能够使用空构造函数而不是列出的构造函数,因为无论如何它都不会发送它。

For simplicity, I'll just quote an explanation from a Connect item:

You can actually configure the
SmtpClient to send emails to the file
system instead of the network. You can
do this programmatically using the
following code:

SmtpClient client = new SmtpClient("mysmtphost");
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = @"C:\somedirectory";
client.Send(message);

You can also set this up in your
application configuration file like
this:

 <configuration>
     <system.net>
         <mailSettings>
             <smtp deliveryMethod="SpecifiedPickupDirectory">
                 <specifiedPickupDirectory pickupDirectoryLocation="C:\somedirectory" />
             </smtp>
         </mailSettings>
     </system.net>
 </configuration>

After sending the email, you should
see email files get added to the
directory you specified. You can then
have a separate process send out the
email messages in batch mode.

You should be able to use the empty constructor instead of the one listed, as it won't be sending it anyway.

澜川若宁 2024-08-09 10:23:36

下面是一个扩展方法,用于将 MailMessage 转换为包含 EML 数据的流。
由于它使用文件系统,这显然有点黑客行为,但它确实有效。

public static void SaveMailMessage(this MailMessage msg, string filePath)
{
    using (var fs = new FileStream(filePath, FileMode.Create))
    {
        msg.ToEMLStream(fs);
    }
}

/// <summary>
/// Converts a MailMessage to an EML file stream.
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static void ToEMLStream(this MailMessage msg, Stream str)
{
    using (var client = new SmtpClient())
    {
        var id = Guid.NewGuid();

        var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);

        tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");

        // create a temp folder to hold just this .eml file so that we can find it easily.
        tempFolder = Path.Combine(tempFolder, id.ToString());

        if (!Directory.Exists(tempFolder))
        {
            Directory.CreateDirectory(tempFolder);
        }

        client.UseDefaultCredentials = true;
        client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
        client.PickupDirectoryLocation = tempFolder;
        client.Send(msg);

        // tempFolder should contain 1 eml file

        var filePath = Directory.GetFiles(tempFolder).Single();

        // stream out the contents
        using (var fs = new FileStream(filePath, FileMode.Open))
        {
            fs.CopyTo(str);
        }

        if (Directory.Exists(tempFolder))
        {
            Directory.Delete(tempFolder, true);
        }
    }
}

然后,您可以获取返回的流并按照您的意愿处理它,包括保存到磁盘上的其他位置或存储在数据库字段中,甚至作为附件通过电子邮件发送。

Here's an extension method to convert a MailMessage to a stream containing the EML data.
Its obviously a bit of a hack as it uses the file system, but it works.

public static void SaveMailMessage(this MailMessage msg, string filePath)
{
    using (var fs = new FileStream(filePath, FileMode.Create))
    {
        msg.ToEMLStream(fs);
    }
}

/// <summary>
/// Converts a MailMessage to an EML file stream.
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static void ToEMLStream(this MailMessage msg, Stream str)
{
    using (var client = new SmtpClient())
    {
        var id = Guid.NewGuid();

        var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);

        tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");

        // create a temp folder to hold just this .eml file so that we can find it easily.
        tempFolder = Path.Combine(tempFolder, id.ToString());

        if (!Directory.Exists(tempFolder))
        {
            Directory.CreateDirectory(tempFolder);
        }

        client.UseDefaultCredentials = true;
        client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
        client.PickupDirectoryLocation = tempFolder;
        client.Send(msg);

        // tempFolder should contain 1 eml file

        var filePath = Directory.GetFiles(tempFolder).Single();

        // stream out the contents
        using (var fs = new FileStream(filePath, FileMode.Open))
        {
            fs.CopyTo(str);
        }

        if (Directory.Exists(tempFolder))
        {
            Directory.Delete(tempFolder, true);
        }
    }
}

You can then take the stream thats returned and do as you want with it, including saving to another location on disk or storing in a database field, or even emailing as an attachment.

折戟 2024-08-09 10:23:36

如果您使用Mailkit。只需编写下面的代码

string fileName = "your filename full path";
MimeKit.MimeMessage message = CreateMyMessage ();
message.WriteTo(fileName);

If you are using Mailkit. Just write below code

string fileName = "your filename full path";
MimeKit.MimeMessage message = CreateMyMessage ();
message.WriteTo(fileName);
一抹淡然 2024-08-09 10:23:36

在社区的帮助下,我提出了.NET 5的解决方案。我已经合并了这个旧解决方案,其中包含建议 帖子并受到 Mailkit 的启发,这产生了很好的扩展方法,没有不必要的依赖项

public static class MailMessageHelper
{
    public static void WriteTo(this MailMessage mail, Stream stream)
    {
        Assembly assembly = typeof(SmtpClient).Assembly;
        Type _mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

        // Get reflection info for MailWriter contructor
        ConstructorInfo _mailWriterConstructor =
            _mailWriterType.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new Type[] { typeof(Stream), typeof(bool) },
                null);

        // Construct MailWriter object with our FileStream
        object _mailWriter =
          _mailWriterConstructor.Invoke(new object[] { stream, true });

        // Get reflection info for Send() method on MailMessage
        MethodInfo _sendMethod =
            typeof(MailMessage).GetMethod(
                "Send",
                BindingFlags.Instance | BindingFlags.NonPublic);

        // Call method passing in MailWriter
        _sendMethod.Invoke(
            mail,
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            new object[] { _mailWriter, true, true },
            null);

        // Finally get reflection info for Close() method on our MailWriter
        MethodInfo _closeMethod =
            _mailWriter.GetType().GetMethod(
                "Close",
                BindingFlags.Instance | BindingFlags.NonPublic);

        // Call close method
        _closeMethod.Invoke(
            _mailWriter,
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            Array.Empty<object>(),
            null);
    }
}

用法

MailMessage mail = new(mailFrom, mailTo, mailSubject, mailContent);
mail.WriteTo(new FileStream(@"path_to_file\new_mail.eml", FileMode.Create));

另外,如果您正在使用 MemoryStream 并希望获得 string 中的结果,只需更改扩展方法的返回类型并在最后写入

return Encoding.ASCII.GetString(stream.ToArray());

Enjoy

With the help of community I came up with an solution for .NET 5. I have combined this old solution with suggestions in this post and got inspired by Mailkit which resulted in nice extension method without unnecessary dependencies

public static class MailMessageHelper
{
    public static void WriteTo(this MailMessage mail, Stream stream)
    {
        Assembly assembly = typeof(SmtpClient).Assembly;
        Type _mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

        // Get reflection info for MailWriter contructor
        ConstructorInfo _mailWriterConstructor =
            _mailWriterType.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new Type[] { typeof(Stream), typeof(bool) },
                null);

        // Construct MailWriter object with our FileStream
        object _mailWriter =
          _mailWriterConstructor.Invoke(new object[] { stream, true });

        // Get reflection info for Send() method on MailMessage
        MethodInfo _sendMethod =
            typeof(MailMessage).GetMethod(
                "Send",
                BindingFlags.Instance | BindingFlags.NonPublic);

        // Call method passing in MailWriter
        _sendMethod.Invoke(
            mail,
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            new object[] { _mailWriter, true, true },
            null);

        // Finally get reflection info for Close() method on our MailWriter
        MethodInfo _closeMethod =
            _mailWriter.GetType().GetMethod(
                "Close",
                BindingFlags.Instance | BindingFlags.NonPublic);

        // Call close method
        _closeMethod.Invoke(
            _mailWriter,
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            Array.Empty<object>(),
            null);
    }
}

Usage

MailMessage mail = new(mailFrom, mailTo, mailSubject, mailContent);
mail.WriteTo(new FileStream(@"path_to_file\new_mail.eml", FileMode.Create));

Also if you are using MemoryStream and want to get result in string, just change the return type of the extension method and at the end write

return Encoding.ASCII.GetString(stream.ToArray());

Enjoy

海之角 2024-08-09 10:23:36

由于某种原因,client.send 失败了(在使用该方法实际发送之后),因此我插入了良好的 'ole CDO 和 ADODB 流。在设置 .Message 值之前,我还必须使用 template.eml 加载 CDO.message。但它有效。

由于上面是 C 语言,这里是 VB 语言

    MyMessage.From = New Net.Mail.MailAddress(mEmailAddress)
    MyMessage.To.Add(mToAddress)
    MyMessage.Subject = mSubject
    MyMessage.Body = mBody

    Smtp.Host = "------"
    Smtp.Port = "2525"
    Smtp.Credentials = New NetworkCredential(------)

    Smtp.Send(MyMessage)        ' Actual Send

    Dim oldCDO As CDO.Message
    oldCDO = MyLoadEmlFromFile("template.eml")  ' just put from, to, subject blank. leave first line blank
    oldCDO.To = mToAddress
    oldCDO.From = mEmailAddress
    oldCDO.Subject = mSubject
    oldCDO.TextBody = mBody
    oldCDO.HTMLBody = mBody
    oldCDO.GetStream.Flush()
    oldCDO.GetStream.SaveToFile(yourPath)

For one reason or another the client.send failed (right after an actual send using that method) so I plugged in good 'ole CDO and ADODB stream. I also had to load CDO.message with a template.eml before setting the .Message values. But it works.

Since the above one is C here is one for VB

    MyMessage.From = New Net.Mail.MailAddress(mEmailAddress)
    MyMessage.To.Add(mToAddress)
    MyMessage.Subject = mSubject
    MyMessage.Body = mBody

    Smtp.Host = "------"
    Smtp.Port = "2525"
    Smtp.Credentials = New NetworkCredential(------)

    Smtp.Send(MyMessage)        ' Actual Send

    Dim oldCDO As CDO.Message
    oldCDO = MyLoadEmlFromFile("template.eml")  ' just put from, to, subject blank. leave first line blank
    oldCDO.To = mToAddress
    oldCDO.From = mEmailAddress
    oldCDO.Subject = mSubject
    oldCDO.TextBody = mBody
    oldCDO.HTMLBody = mBody
    oldCDO.GetStream.Flush()
    oldCDO.GetStream.SaveToFile(yourPath)
桃扇骨 2024-08-09 10:23:36

尝试一下

,请使用这 2 个参考
(使用 MailBee;)
(使用MailBee.Mime;)

    public static string load(string to,string from,string cc,string bcc,string subject,string body, List<string> reportList,string path, bool HtmlbodyType)
    {
        try
        {
            MailBee.Mime.MailMessage msg = new MailBee.Mime.MailMessage();
            msg.From.AsString = from;
            msg.Subject = subject;
            if (HtmlbodyType == true)
            {
                msg.BodyHtmlText = body;
            }
            else
            {
                msg.BodyPlainText = body;
            }
            
            string[] receptionEmail = to.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string[] ccEmail = cc.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string[] bccEmail = bcc.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string message = "";
            foreach (string To in receptionEmail)
            {
                msg.To.Add(To);
            }
            foreach (string CC in ccEmail)
            {
                    msg.Cc.Add(CC);
            }
            foreach (string Bcc in bccEmail)
            {
                    msg.Bcc.Add(Bcc);

            }
                for (int x = 0; x < reportList.Count; x++)
                {
                    string fileName = reportList[x];
                    msg.Attachments.Add(fileName);
                }

                msg.SaveMessage(path);
                return "Success";
            
        }
        catch (Exception ex)
        {
            return ex.Message;
        }

    }

try this

please use these 2 reference
( using MailBee;)
( using MailBee.Mime;)

    public static string load(string to,string from,string cc,string bcc,string subject,string body, List<string> reportList,string path, bool HtmlbodyType)
    {
        try
        {
            MailBee.Mime.MailMessage msg = new MailBee.Mime.MailMessage();
            msg.From.AsString = from;
            msg.Subject = subject;
            if (HtmlbodyType == true)
            {
                msg.BodyHtmlText = body;
            }
            else
            {
                msg.BodyPlainText = body;
            }
            
            string[] receptionEmail = to.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string[] ccEmail = cc.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string[] bccEmail = bcc.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
            string message = "";
            foreach (string To in receptionEmail)
            {
                msg.To.Add(To);
            }
            foreach (string CC in ccEmail)
            {
                    msg.Cc.Add(CC);
            }
            foreach (string Bcc in bccEmail)
            {
                    msg.Bcc.Add(Bcc);

            }
                for (int x = 0; x < reportList.Count; x++)
                {
                    string fileName = reportList[x];
                    msg.Attachments.Add(fileName);
                }

                msg.SaveMessage(path);
                return "Success";
            
        }
        catch (Exception ex)
        {
            return ex.Message;
        }

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文