开发者

How to send email in the Background in AsP.NET?

I am using ASP.NET Web forms,

When a user submit a page, an email will be sent to many people开发者_StackOverflow社区 which is slowing the post-back,

what is the best way to send the emails without slowing the reloading of the page?

thanks


You can use the System.Net.Mail.SmtpClient class to send the email using the SendAsync() method.

var smtpClient = new SmtpClient();
var message = new MailMessage(fromAddress, toAddress, subject, body);
smtpClient.SendCompleted += new SendCompletedEventHandler(OnSendCompletedCallback);
smtpClient.SendAsync(message, null); // Null Or pass a user token to be send when the send is complete

If you need to handle perform some additional stuff after the async send is complete you can subscribe to the SendCompleted event of the SmtpClient as well.

private void OnSendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
     // Handle the callback if you need to do anything after the email is sent.
}

Here is a link to the documentation on MSDN.


I've found unless you're building a very small website, it's almost always best to send mail from a separate Windows Service.

Your Web front-end logs the mail to be sent in your database for example. This has a nice side-effect of allowing you do also develop an sent folder, outbox, etc. Your windows service polls the mail table and does the actual sending.

Sending mail can cause lots of exceptions, can be slow, can timeout, host processes reaped, etc. Handling it in the background makes a lot of sense in many situations.

Here's more information on Windows Services.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜