在后台发送来自asp.net的邮件

时间:2011-07-08 20:38:17

标签: asp.net

我正在开发一个网站,我需要在他按下提交按钮后向客户端发送邮件。但其次我不希望客户端等到邮件发送然后他进入下一页。 一旦他按下提交按钮,他就应该被重定向到下一页,而在后台则会发送邮件。

我尝试过异步发送邮件。在下面的代码中,它会发送邮件。当操作完成后,它会将客户端重定向到About.aspx。

    MailMessage m = new MailMessage();
    MailAddress emailsender = new MailAddress(senderemail.Text, "User");
    m.From = emailsender;
    MailAddress recipient = new MailAddress(dest.Text);
    m.To.Add(recipient);
    m.Body = message.Text.ToString();
    m.Subject = subj.Text;
    SmtpClient client = new SmtpClient();
    //Add the Creddentials- use your own email id and password

    client.Credentials = new System.Net.NetworkCredential(senderemail.Text,password.Text);

    client.Port = 587; // Gmail works on this port
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true; //This enables the SSL
    Object usertoken=m;
    client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

    try
    {
        client.SendAsync(m, usertoken);
    }
    catch (Exception ex)
    {
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
        {
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        }
        HttpContext.Current.Response.Write(errorMessage);
    } // end try 
  void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    MailMessage mail = e.UserState as MailMessage;
    Response.Redirect("About.aspx");

    if (!e.Cancelled && e.Error != null)
    {
        lblMessage.Text = "Mail sent successfully";
    }

}

2 个答案:

答案 0 :(得分:1)

如果您不想等待发送的邮件,那么您应该在调用SendAsync()方法后立即重定向(而不是在SendCompleted处理程序中):

client.SendAsync(m, usertoken);
lblMessage.Text = "Mail sent";
Response.Redirect("About.aspx");

答案 1 :(得分:0)

将所有代码放在threadPool中:

ThreadPool.QueueUserWorkItem(o => { 

//your code here.....

});

对我而言,它运作良好。