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

 

Published 19 March 2007 11:54 AM by haissam

Comments

# sonu said on 19 March, 2007 01:00 PM

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

# haissam said on 19 March, 2007 01:48 PM

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

# Bilal said on 23 March, 2008 01:57 AM

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.

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Breaking News
  • Find a Job
  • Social Bookmarking
    Tidebuy Reviews
    Online Shopping
    asp.net hosting
    UK online local dating