叫我試圖以異步方式發送電子郵件,但是當我把我的SendMailMesage()方法從一個線程池或一個簡單的線程內,電子郵件根本不會發送時不被髮送。Gmail電子郵件從一個線程池
任何方式如何實現這一目標?定期發送電子郵件sendind會大大減慢我的應用程序。
PS:如果它很重要,SendMailMesage()正在從引用的項目發送,而不是MVC項目本身。
謝謝。
編輯:我的代碼。
namespace App.Core.Utils.Mailer
{
public static class Sender
{
/// <summary>
/// Sends a MailMessage object using the SMTP settings.
/// </summary>
public static void SendMailMessage(MailMessage message)
{
if (!Settings.Instance.SendEmails)
{
return;
}
if (message == null)
throw new ArgumentNullException("message");
try
{
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
var smtp = new SmtpClient(Settings.Instance.SmtpServer);
// don't send credentials if a server doesn't require it,
// linux smtp servers don't like that
if (!string.IsNullOrEmpty(Settings.Instance.SmtpUserName))
{
smtp.Credentials = new System.Net.NetworkCredential(Settings.Instance.SmtpUserName, Settings.Instance.SmtpPassword);
}
smtp.Port = Settings.Instance.SmtpServerPort;
smtp.EnableSsl = Settings.Instance.EnableSsl;
smtp.Send(message);
}
catch (SmtpException)
{
//OnEmailFailed(message);
}
finally
{
// Remove the pointer to the message object so the GC can close the thread.
message.Dispose();
}
}
public static void SendMailMessageAsync(MailMessage message)
{
ThreadPool.QueueUserWorkItem(state => SendMailMessage(message));
}
}
}
請注意:這工作在WebForms。我將代碼複製到一個MVC項目中,現在如果我調用SendMailMessageAsync
方法,則不會發送任何內容。沒有錯誤。
當它沒有被調用在線程池中時它工作嗎? – casperOne 2012-02-09 02:39:42