views:

63

answers:

2

Hi Guys,

I am using ASP.NET Web forms,

When a user submit a page, an email will be sent to many people which is slowing the post-back,

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

thanks

+4  A: 

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.

Wallace Breza
A: 

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.

kervin
actually It is a small website, thanks for the tip
user1111111