我正在尝试使用 C# 代码发送和保存发送的电子邮件。但我做不到。我可以保存邮件,也可以发送邮件。但我无法同时完成这两件事。
这是我的:
public ActionResult Index()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("test@mail.com");
message.To.Add(new MailAddress("mymail@gmail.com"));
message.Subject = "Test Subject";
message.Body = "This is a test message";
message.IsBodyHtml = true;
// Setup SMTP settings
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
NetworkCredential basicCredential = new NetworkCredential("mymail@gmail.com", "******");
smtp.UseDefaultCredentials = false;
smtp.Credentials = basicCredential;
smtp.Send(message);
// save
smtp.EnableSsl = false;
smtp.PickupDirectoryLocation = @"C:\Temp";
smtp.Send(message);
return View();
}
所以首先我尝试发送电子邮件。这样可行。然后我试图将电子邮件保存到我的硬盘。但它永远不会被保存。当我不发送电子邮件并尝试立即将其保存到我的硬盘时,它确实有效。但我需要两者兼顾。
有人知道我该如何完成吗?我只需要记录发送消息。
最佳答案
拾取目录中的邮件消息由本地 SMTP 服务器(如果存在)自动发送,例如 IIS。 ( SmtpClient.PickupDirectoryLocation )
如果要保存到文件系统,需要将DeliveryMethod
设置为SmtpDeliveryMethod.SpecifiedPickupDirectory
:
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = @"C:\Temp";
client.Send(message);
参见 How to save MailMessage object to disk as *.eml or *.msg file
关于c# - 使用 System.Net.Mail 保存和发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12154975/