Sending email through C#

sending email through C#:
Let's see the code to send an email. This code is executed on the button click control. First of all don't forget to add the
using System.Web.Mail;
namespace which provides the methods and properties for sending an email.

private void Button1_Click(object sender, System.EventArgs e)
MailMessage mail = new MailMessage();
mail.To = txtTo.Text; //put the TO ADDRESS here.
mail.From = txtFrom.Text; //put the FROM ADDRESS here.
mail.Subject = txtSubject.Text; //put the SUBJECT here.
mail.Body = txtBody.Text; //put the BODY here.
SmtpMail.SmtpServer = "localhost"; //put SMTP SERVER you will use here.

Description of the above Code:
The code you see above is very simple to understand. In the button click event we made the object/instance of the MailMessage class. MailMessage is responsible for sending emails. It also provides several properties and methods. Later we assigned several properties.

The line SmtpMail.SmtpServer = "localhost" sets the server for the mail. If you are running the application on your own PC using IIS than your server will be "localhost". If your website is running on the production server you can have different SmtpServer name.

The final line SmtpMail.Send(mail) sends the email to the email address provided.


  • 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: