How to send Email in ASP.net:

Jun 1, 2012 By Anil Gaikwad
  • To send mails from asp.net first define a MailMessage Object, which provides properties and methods for constructing an e-mail message. Which you can find under “System.Web.Mail” namespace
MailMessage mail = new MailMessage();
  • Next step in sending Email is creating object of class SmtpClient which allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
SmtpClient SmtpServer = new SmtpClient();
  • After that add requiredTo address, From Address, CC Address, BCC Address, Subject, Body to mail object which we have created in first step.
mail.To.Add(txtTolist.Text); mail.From = new MailAddress(txtFrom.Text); mail.Subject = txtSubject.Text; mail.Body = txtBody.Text;
  • To add attachment use attachment object and pass file path to it.
mail.Attachments.Add(new Mail.Attachment(Attachment[i].ToString()));
  • Provide port and host name to SmtpClient object using which you will be sending the mail.
SmtpServer.Port = "";//port no SmtpServer.Host = "localhost"; //Host name
  • And at Last execute send function of SmtpClient to send the mail only pass mail Object to it
SmtpServer.Send(mail);

Complete Code Example:

MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(); mail.To.Add(txtTolist.Text); mail.From = new MailAddress(txtFrom.Text); mail.Subject = txtSubject.Text; mail.Body = txtBody.Text; mail.Attachments.Add(new Mail.Attachment(Attachment[i].ToString())); SmtpServer.Port = "";//port no SmtpServer.Host = "localhost"; //Host name SmtpServer.Send(mail);