How to Send Emails from .Net [example uses GMail SMTP]
We frequently see questions about sending emails using .Net in the asp.net forums. The process of sending mail is the same for Windows apps and asp.net websites as the same .Net classes are used. The process can be slightly shortened by specifying default SMTP settings in the web.config or app.config file. Here, I’m showing the full version of the code and it does not rely on any configuration settings. The code also specifies unicode encoding for the subject and body.
using System.Net.Mail;
using System.Net;
//Create the mail message
MailMessage mail = new MailMessage();
mail.Subject = "Subject";
mail.Body = "Main body goes here";
//the displayed "from" email address
mail.From = new System.Net.Mail.MailAddress(you@live.com);
mail.IsBodyHtml = false;
mail.BodyEncoding = System.Text.Encoding.Unicode;
mail.SubjectEncoding = System.Text.Encoding.Unicode;
//Add one or more addresses that will receive the mail
mail.To.Add("me@live.com");
//create the credentials
NetworkCredential cred = new NetworkCredential(
"you@live.com", //from email address of the sending account
"password"); //password of the sending account
//create the smtp client...these settings are for gmail
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
//credentials (username, pass of sending account) assigned here
smtp.Credentials = cred;
smtp.Port = 587;
//let her rip
smtp.Send(mail);
Hope that helps.
EDIT: I just added the namespaces. MailMessage exists in both System.Net.Mail and System.Web.Mail. System.Web.Mail has been deprecated and you should use System.Net.Mail.