我想知道是否有一种在asp.net c#中异步发送电子邮件的方法。我已经使用以下代码发送电子邮件:
if (checkObavijest.Checked)
{
List<hsp_Kupci_Newsletter_Result> lista = ServisnaKlasa.KupciNewsletter();
for (int i = 0; i < lista.Count; i++)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("*******");
mail.To.Add(lista[i].Email);
mail.Subject = "Subject";
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
mail.Body = "Some message";
SmtpClient smtpClient = new SmtpClient();
Object state = mail;
smtpClient.Credentials = new NetworkCredential("****@gmail.com", "****");
smtpClient.Port = 587;
smtpClient.Host = "smtp.gmail.com";
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.SendAsync(mail, state);
}
catch (Exception ex)
{
}
}
void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
MailMessage mail = e.UserState as MailMessage;
if (!e.Cancelled && e.Error != null)
{
string poruka = "Emailovi poslani!";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + poruka + "');", true);
}
}
但是当我勾选发送电子邮件选项时,页面会加载约40秒钟,然后在40秒后才会发送电子邮件。您可以看到,我目前从我的数据库中提取了20-30封电子邮件。我以为这是异步发送邮件的正确方法,但显然不是...我该如何将电子邮件发送推送到另一个线程,以便不影响正在使用此页面的用户?有人能帮帮我吗?谢谢!
smtpclient
相关的代码,然后只需调用SendViaThread(mail)
而不是smtpClient.SendAsync(mail, state)
即可。 - AbhitalksSendViaThread(mail)
。我正在更新答案,以包括您这一侧的代码。 - Abhitalks