如何将 MailMessage 对象保存到磁盘?MailMessage 对象不公开任何 Save() 方法。
如果它以任何格式保存,*.eml 或 *.msg,我没有问题。知道怎么做吗?
如何将 MailMessage 对象保存到磁盘?MailMessage 对象不公开任何 Save() 方法。
如果它以任何格式保存,*.eml 或 *.msg,我没有问题。知道怎么做吗?
为简单起见,我将仅引用Connect 项的解释:
您实际上可以将 SmtpClient 配置为将电子邮件发送到文件系统而不是网络。您可以使用以下代码以编程方式执行此操作:
SmtpClient client = new SmtpClient("mysmtphost"); client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; client.PickupDirectoryLocation = @"C:\somedirectory"; client.Send(message);
您也可以在应用程序配置文件中进行设置,如下所示:
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\somedirectory" />
</smtp>
</mailSettings>
</system.net>
</configuration>
发送电子邮件后,您应该会看到电子邮件文件已添加到您指定的目录中。然后,您可以让一个单独的进程以批处理模式发送电子邮件。
您应该能够使用空构造函数而不是列出的构造函数,因为无论如何它都不会发送它。
这是将 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);
}
}
}
然后,您可以获取返回的流并按照您的意愿使用它,包括保存到磁盘上的另一个位置或存储在数据库字段中,甚至作为附件发送电子邮件。
如果您使用的是Mailkit。只需写下面的代码
string fileName = "your filename full path";
MimeKit.MimeMessage message = CreateMyMessage ();
message.WriteTo(fileName);
在社区的帮助下,我想出了一个.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());
享受
由于某种原因,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)
试试这个
请使用这 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;
}
}