Sending Email Using System.Net.Mail

If you are in a process when a Contact Us form is needed, you have to give your users the ability to contact you by sending their comments, feedbacks, etc... Microsoft has provided classes to enable sending email. Before we hit the code, you need to configure your Smtp Server. I found a good faq which will guide you through the steps to configure your smtp server and a lot of more additional help.

First of all, you need to import the namespace System.Net.Mail.

using System.Net.Mail;

Second We will create a method which will do our purpose. This method takes 3 string parameters.

   internal void SendEmail(string emailAddress, string subject, string body)
    {
 // Create an instance of the MailMessage Class
        MailMessage contMail = new MailMessage();
 
 // Set from whom the email is sent

        contMail.From = new MailAddress(emailAddress);

 // Set to whom the email is sent. This variable is saved in the web.config
        contMail.To.Add(ConfigurationManager.AppSettings["To"].ToString());

 // Set the subject. this value is retrieved from the paramaters
        contMail.Subject = subject;

 // Set the content of the email.
        contMail.Body = body;

 // Create a new instance of SmtpClient Class. You can replace 127.0.0.1 by localhost
        SmtpClient email = new SmtpClient("127.0.0.1");

 // Send the email
        email.Send(contMail);

    }

After creating the method, You just need to call it whenever you need to.

Don't forget to modify the web.config, just add the below code under the configuration tag.


 <appSettings>
  <add key="To" value="haissam50@hotmail.com"/>
 </appSettings>

Best Regards,

HC

 

Comments

# re: Sending Email Using System.Net.Mail

Monday, March 19, 2007 1:00 PM by sonu

Don't forget that the web.config in 2.0 contains a new section to store SMTP Settings. It can be used to set the SMTPPort,  host, defaultCredentials etc..

Checkout the msdn for: mailSettings

# re: Sending Email Using System.Net.Mail

Monday, March 19, 2007 1:48 PM by haissam

I'm actually aware of this new section, but in this example we didnt need to use it that is why it is not mentioned :)

Best Regards,

HC

# re: Sending Email Using System.Net.Mail

Sunday, March 23, 2008 1:57 AM by Bilal

Hi,

Thanks for the code snippet. I tried to use it but I am getting exception saying SMPT requires authentication to send mail.

Can you suggest what can be done here.

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.