How to Send Emails from .Net [example uses GMail SMTP]

by ashic 28. April 2009 00:10

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.

Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: .NET | ASP.NET

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0
Theme by Ashic Mahtab

Need an expert?

Ashic Mahtab
ashic@live.com
(+44) 07879927393

Stats

Featured Ads

 

Donations

I maintain this site and create all content entirely in my own time just to help you guys out. If you find the stuff helpful, or cool or just like what you see, I'd appreciate you chipping in to help out with the hosting costs. It's easy to do so - just click the button below - no amount is too low :)