开发者

Send mail from asp.net in background

I am developing a website in which I need to send a mail to the client after he presses the submit button.But secondly I dont want the client to wait until the mail is sent and then he is advanced to the next page. As soon as he presses the Submit Button,he should be redirected to next page,while in the background the mail is being sent.

I have tried sending mail Asynchronously.In the code below 开发者_JS百科,it sends the mail.When the operation completes it redirects the client to 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";
    }

}


If you don't want to wait for the mail being sent, then you should redirect immediately after invoking the SendAsync() method (instead of in the SendCompleted handler):

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


Put all your code in threadPool:

ThreadPool.QueueUserWorkItem(o => { 

//your code here.....

});

For me it works fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜