loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Sending email programmatically with gmail :: tutorial

by naspinski 1/25/2008 3:48:00 PM

worry about smtp servers/settings no longer; completely portable code for sending email with gmail and asp.net

I have used a ton of different hosts, and it always seems to be a hassle to find out their information on their smtp servers... not to mention all of your programs are broken if you move them.  With .net, you don't need to use anything but gmail's own protocols in order to make fully portable code that sends emails, and it is oh-so-simple!  I use this from everything from contact pages to email notifications to myself on errors and such - hope it helps.

 

First thing you need to do is declare you will be using the System.Net.Mail namespace as the System.Web.Mail is deprecated as of the past year or so.

 

Next, you simply have to make a new MailMessage and set its properties like To, From, Body, Subject, etc.  here is an example with all static input:

 

MailMessage email = new MailMessage();
email.To.Add("to@address.com");
MailAddress maFrom = new MailAddress("from@address.com");
email.From = maFrom;
email.Body = txtMessage.Text;
email.IsBodyHtml = true;//this is only if you are sending an html message
email.Subject = txtSubject.Text;

 

Now that the message is made, all you have to do is set your smtp credentials, and push the message out:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25);
smtp.EnableSsl = true;

smtp.Credentials = new System.Net.NetworkCredential("address@gmail.com", "password");

smtp.Send(email);

 

That's it!  It is just that easy... 

 

You can get a fully working example here:

 


Related posts


Comments are closed