Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0

  • Home
  • Blog
  • Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0

Posted by Jalpesh Vadgama |  July 16, 2009 |  ASP.NET, C#.NET |  19 comments    For any web application or website the sending email is a necessity for newsletter, invitation or reset password for everything we have to sent a mail to the people. So we need to see how we can send mail. In 1.1 we are sending emails with System.Web.Mail.SmtpMail which is now obsolete. Now in asp.net 2.0 or higher version there is a namespace called System.Net.Mail.Smtpmail in asp.net 3.5. With this namespace we can easily write a code to send mail within couple of minutes. If you want to sent a mail first thing you need is smtpserver. Smtpserver is a server which will route and send mail to particular system. To use smtpserver we need to configure some settings in web.config following is the setting for the web.config.


    

       

         

             

    



Here you need to set the all the smtp configuration. This will be used by the smptclient by default. Here is the code for sending email in asp.net 3.5

SmtpClient smtpClient = new SmtpClient(); MailMessage message = new MailMessage(); try { MailAddress fromAddress = new MailAddress("[email protected]","Nameofsendingperson"); message.From = fromAddress;//here you can set address message.To.Add("[email protected]");//here you can add multiple to message.Subject = "Feedback";//subject of email message.CC.Add("[email protected]");//ccing the same email to other email address message.Bcc.Add(new MailAddress("[email protected]"));//here you can add bcc address

   message.IsBodyHtml = false;//To determine email body is html or not

   message.Body =@"Plain or HTML Text";

   smtpClient.Send(message);

}

catch (Exception ex)

{

   //throw exception here you can write code to handle exception here

}

So from above simple code you can add send email to anybody Adding Attachment to the email:If you want to attach some thing in the code then you need to write following code.

message.Attachments.Add(New System.Net.Mail.Attachment(Filename));

Here file name will the physical path along with the file name. You can attach multiple files with the mail. Sending email with Authentication: If you want to sent a email with authentication then you have to write following code.

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();

     //This object stores the authentication values

     System.Net.NetworkCredential basicCrenntial = 
          new System.Net.NetworkCredential("username", "password");

     mailClient.Host = "Host";

     mailClient.UseDefaultCredentials = false;

     mailClient.Credentials = basicCrenntial;

     mailClient.Send(message);

Happy Coding…