我编写了一些简单的代码,使用 System.mail.Net 命名空间发送自动生成的电子邮件。
它的效果很好,但有一个小问题。
邮件不会发送,直到我的整个应用程序终止。
你们有解决办法吗?
这是我使用的代码 (c#):
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("myEmail@mail.com");
mail.To.Add("targetEmail@mail.com");
mail.Subject = "Test test";
mail.Body = "blah blah";
mail.Attachments.Add(new Attachment("c:\\file.txt"));
SmtpClient smtp = new SmtpClient("myserver.mail.com");
smtp.Send(mail);
}
catch (SmtpFailedRecipientsException ex)
{
Console.WriteLine(ex);
}
正如我所说,一切正常,但邮件不会发送,直到我终止应用程序。
有没有办法强制它现在发送邮件?
这是一个问题,因为我希望邮件立即发送而不需要用户重新启动应用程序,而且因为我想在邮件发送后删除附件,当邮件未发送,因此文件被标记为“正在使用”,因此无法删除。
最好的问候
/小号
请您参考如下方法:
我遇到了同样的问题,并使用了在 http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/6ce868ba-220f-4ff1-b755-ad9eb2e2b13d/ 上发布的解决方法似乎有效:
For anyone interested, I've found a solution or at least a work around to the delay.
The ServicePoint member contains a member called MaxIdleTime. Setting this value to 0 seems to have the same affect as Timeout.Infinite (which I assume is also 0). Setting it to 1 caused my email to be sent out immediately.
See this link:
http://msdn2.microsoft.com/en-us/library/system.net.servicepoint.maxidletime.aspx
Example code:
SmtpClient smtp = new SmtpClient();
// setup the mail message
smtp.ServicePoint.MaxIdleTime = 1;
smtp.Send(myMailMessage);
