Send Email From C#

Now throw this junk of code we can able to send email. 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

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


Cheers,
Feel free to send your opinion.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: