How to Sending Email Asynchronously .net 3.5

Now throw this junk of code we can able to send email Asynchronously Its a method you can call this method in any event

We take host name from web.config you can find the code below

private void SendMail()
{

//Create message object and populate with the data from form
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress(txtFrom.Text.Trim());
message.To.Add(txtTo.Text.Trim());
message.Subject = txtSubject.Text.Trim();
message.Body = txtBody.Text.Trim();

//Setup SmtpClient to send email. Uses web.config settings.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

//Error handling for sending message
try
{
smtpClient.Send(message);
//Exception contains information on each failed receipient
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
for (int recipient = 0; recipient < recExc.InnerExceptions.Length - 1; recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;

statusCode = recExc.InnerExceptions[recipient].StatusCode;

if ((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable))
{

System.Threading.Thread.Sleep(5000);
smtpClient.Send(message);
}
else
{
ErrorLabel.Text = recExc.Message;


}

}
}
//General SMTP execptions
catch (System.Net.Mail.SmtpException smtpExc)
{

ErrorLabel.Text = smtpExc.StatusCode.ToString();
}
catch (Exception ex)
{
//Log error to event log.
}
}

Configuring web.config file


&lt system.net>
&lt mailSettings>
&lt smtp>
&lt network host="YOUR HOST INFO HERE"/>
&lt /smtp>
&lt /mailSettings>
&lt /system.net>

No comments: