c# - 使用 System.Net.Mail 保存和发送邮件

标签 c# .net 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();
}

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

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

最佳答案

拾取目录中的邮件消息由本地 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/

相关文章:

c# - 当 WCF 方法返回集合时 ServiceKnownType 出现异常

c# - 父节点内列表的序列化(集合扁平化)

html - Logo 应该是 html 电子邮件中的单独图像吗?

C#:DateTime.Now 月份输出格式

c# - 重定向到当前友好的 URL(有或没有 url 变量)

.net - 在 vs 中调试时的本地化

c# - 根据参数在 Razor 中切换 Case

c# - 仅当值在运行时使用 Unity 为非空时,如何才能注入(inject)属性?

css - Aweber 电子邮件模板,在 outlook 中宽度乱七八糟

java - 未送达邮件的原始邮件 header