HeartattacK

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.

Posted: Apr 28 2009, 12:10 PM by HeartattacK | with 3 comment(s)
Filed under: , ,

Comments

Web Development Community said:

You are voted (great) - Trackback from Web Development Community

# April 28, 2009 5:17 AM

Jason Roner said:

Hey Thanks!  Seems to work in a webform.  The only thing not working is the subject line which only displays the first character of the entire line in my email inbox.  For example, if I put in "New Form Submission", then I will only see "N" as the subject in my received email.

# June 19, 2009 8:30 PM

yash said:

How to add attachement using the same code logic

# October 16, 2009 10:18 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)