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