How to send email in the background in AsP.NET?
You can use the System.Net.Mail.SmtpClient class to send 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 some additional stuff after the asynchronous dispatch completes, you can subscribe to the SendCompleted event for the SmtpClient.
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 MSDN documentation.
a source to share
I have found that if you are building a very small website, it is almost always better to send mail from a separate Windows service.
Your web interface logs mail sent to your database for example. This has a nice side effect of allowing you to create a sent folder, outgoing mail, etc. The Windows service checks the mail table and performs the actual submission.
Sending mail can throw a lot of exceptions, it can be slow, it can time out, process host processes, etc. Processing it in the background makes a lot of sense in many situations.
Here's more information about Windows Services .
a source to share