Sending email programmatically with gmail :: tutorial

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

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();
MailAddress maFrom = new MailAddress("");
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("", 25);
smtp.EnableSsl = true;

smtp.Credentials = new System.Net.NetworkCredential("", "password");



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


You can get a fully working example here:


Add comment