使用 System.Net.Mail 保存并发送邮件

w00*_*w00 4 .net c# email smtp

我正在尝试使用 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();
}
Run Code Online (Sandbox Code Playgroud)

所以首先我尝试发送电子邮件。这样可行。然后我尝试将电子邮件保存到我的硬盘上。但它永远不会被保存。当我不发送电子邮件并尝试立即将其保存到我的硬盘时,它确实有效。但我需要两者都做。

有人知道我该如何完成这件事吗?我只需要记录发送消息。

Mit*_*eat 5

拾取目录中的邮件消息由本地 SMTP 服务器(如果存在)(例如 IIS)自动发送。(SmtpClient.PickupDirectoryLocation

如果你想保存到文件系统,你需要设置DeliveryMethodSmtpDeliveryMethod.SpecifiedPickupDirectory

client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; 
client.PickupDirectoryLocation = @"C:\Temp"; 
client.Send(message); 
Run Code Online (Sandbox Code Playgroud)

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