Click here to Skip to main content
Click here to Skip to main content

Sending Email with Gmail, Yahoo, AOL, and Live Mail Via SMTP

By , 27 May 2010
 

Introduction

My name is Charles Henington and I will be showing you how to send email with C# Winform via Gmail, Yahoo and Windows Live accounts. These will be sent using SMTP and will all use the same basic lines of code with slight variations.

Acknowledgements

This code is built based on a simple email app built by a good guy named Abhishek Sur. His article can be found here.

Getting Started

You will need 5 textboxes, 6 labels, 1 listbox, and 3 buttons. You will leave all items as default names example (textBox1, textBox2, etc.) change text on label1 to (TO). Change label2 text to (GMAIL ACCT), label3 to (Password), label4 to (Subject), label5 to (Message body). Label 1-5 will go with the appropriate text box 1-5. Now change button1 text to (Add Attachment), button2 to (Remove Attachment), and button3 to (Send Mail). Now take textBox5 and make it multiline and stretch it out until your text box resembles a text area. Now add a listBox this list box will handle your attachments and change label6 to (Attachments).

Using the Code

Using the code is very self explanatory if you have left the default names like I had mentioned earlier.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net.Mime;

		namespace EmailClient
	{
		public partial class GoogleForm : Form
	{
		MailMessage mail = new MailMessage();
		public GoogleForm()
	{
		InitializeComponent();
	}            
		private void button1_Click(object sender, EventArgs e)
	{
		smtp_csharp.frmAddAttachment frm = new smtp_csharp.frmAddAttachment();
		frm.ShowDialog(this);
		if (frm.txtFile.Text.Trim() != "")
		listBox1.Items.Add(frm.txtFile.Text);
		frm.Dispose();
	}
		private void button2_Click(object sender, EventArgs e)
	{
		if (listBox1.SelectedIndex > -1)
		listBox1.Items.RemoveAt(listBox1.SelectedIndex);
	}
		private void button3_Click(object sender, EventArgs e)
	{
		using (MailMessage mailMessage = 
			new MailMessage(new MailAddress(textBox1.Text),
		new MailAddress(textBox1.Text)))
	{
		mailMessage.Body = textBox5.Text;
		mailMessage.Subject = textBox4.Text;
		try
	{
		SmtpClient SmtpServer = new SmtpClient();
		SmtpServer.Credentials = 
		    new System.Net.NetworkCredential(textBox2.Text, textBox3.Text);
		SmtpServer.Port = 587;
		SmtpServer.Host = "smtp.gmail.com";
		SmtpServer.EnableSsl = true;
		mail = new MailMessage();
		String[] addr = textBox1.Text.Split(',');
		mail.From = new MailAddress(textBox2.Text);
		Byte i;
		for (i = 0; i < addr.Length; i++)
		mail.To.Add(addr[i]);
		mail.Subject = textBox4.Text;
		mail.Body = textBox5.Text;
		if (listBox1.Items.Count != 0)
	{
		for (i = 0; i < listBox1.Items.Count; i++)
		mail.Attachments.Add(new Attachment(listBox1.Items[i].ToString()));
	}
		mail.IsBodyHtml = true;
		mail.DeliveryNotificationOptions = 
			DeliveryNotificationOptions.OnFailure;
		mail.ReplyTo = new MailAddress(textBox1.Text);
		SmtpServer.Send(mail);	
	}
		catch (Exception ex)
	{
		MessageBox.Show(ex.Message, "EMail", 
		    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
	}
      }
  }

Attachment Form

For the Attachment Form, make a new form and add 1 text box With Name (txtFile), and 3 buttons. The first button will have Name btnBrowse and text Browse, the second button will have Name btnOK and text OK, the third button will have Name btnCancel and text Cancel. The code for this form will be:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace smtp_csharp
	{
		/// <summary>
		/// Summary description for frmAddAttachment.
		/// </summary>
		public class frmAddAttachment : System.Windows.Forms.Form
	{
		internal System.Windows.Forms.Button btnCancel;
		internal System.Windows.Forms.Button btnOK;
		internal System.Windows.Forms.Button btnBrowse;
		internal System.Windows.Forms.OpenFileDialog dlg;
		public System.Windows.Forms.TextBox txtFile;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		public frmAddAttachment()
	{
		//
		// Required for Windows Form Designer support
		//
		InitializeComponent();
		//
		// TODO: Add any constructor code after InitializeComponent call
		//
	}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
	{
		if( disposing )
	{
		if(components != null)
	{
		components.Dispose();
	}
	}
		base.Dispose( disposing );
	}
		private void btnBrowse_Click(object sender, System.EventArgs e)
	{
		dlg.ShowDialog();
		txtFile.Text = dlg.FileName;
	}
		private void btnOK_Click(object sender, System.EventArgs e)
	{
		this.Hide();
	}
		private void btnCancel_Click(object sender, System.EventArgs e)
	{
		txtFile.Text = "";
		this.Hide();
	}
      }
   }

Now to send the message with Yahoo, the code will remain the same except change 2 lines of code.

The original code to be changed is:

SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;

The above code should be changed to:

SmtpServer.Host = "smtp.mail.yahoo.com";
SmtpServer.EnableSsl = false;

You can now send email via Gmail and Yahoo. Live mail is a little trickier since it uses SSL and SPA.

But we will add 2 lines of code and change 1 line of code from the original Gmail app.

The original line of code to be changed is:

SmtpServer.Host = "smtp.gmail.com";

The above code should be changed to:

SmtpServer.Host = "smtp.live.com";

Now we will add 2 lines of code to our app:

The first code should be added to the button3 click event between:

SmtpClient SmtpServer = new SmtpClient();

and:

NetworkCredential cred = new NetworkCredential(textBox2.Text, textBox3.Text);

The code to be added is:

SmtpServer.Credentials=new System.Net.NetworkCredential(textBox2.Text, textBox3.Text);

The final code to be added is:

using System.Net;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

charles henington
United States United States
Member
I do not claim to be wrong! I just rarely ever write.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionGreat! Just what I was looking formembergcode111 Apr '13 - 6:09 
This is what I've been struggling to find for ages... btw how do I send from an Outlook.com account?
Questiondoes not work for LIVEmemberzinxx8 Jan '13 - 2:25 
any updated code so that it works with hotmail sender ???
GeneralMy vote of 4membercsharpbd19 Nov '12 - 20:24 
Good but need more description...
GeneralMy vote of 1memberChewsHumans6 Feb '12 - 5:31 
Would have rated higher but DOWNLOAD LINKS ARE BROKEN
GeneralMy vote of 1memberdvptUml16 Apr '11 - 23:48 
Error downloads
No sourcecode files
GeneralMy vote of 1memberFreax Domino30 Nov '10 - 10:54 
Actually, the web seems to be full of examples on how to do what you're trying to show here (Google "c# send email smtp" and you'll get >700,000 results: some of those *ought* to be good).
GeneralRe: My vote of 1membercharles henington17 Mar '11 - 18:33 
then use one of those really a 1 because there other examples there is examples all over the internet on how to do anything why dont you go waste your time and vote everyone a 1 if you dont need the example then dont waste your time voting and move on down the road
Generalvery good article thanks but can't download the codememberHasbi Allah22 Oct '10 - 6:35 
can you pleas update the sourcecode links
GeneralVery Goodmemberrspercy603 Jun '10 - 17:10 
I added a skin to the app and changed a few things, but in all a very short, simple and to the point article.
I gave you 5 circles because I did learn something from this app and that was how to use System.Net
Namespace and classes. You dont see them very often in books on VB and C#.
rspercy
1 + 1 = 184,000, Depending on the species.

GeneralRe: Very Goodmembercharles henington3 Jun '10 - 22:26 
Thanks much sir I appreciate the kind words and yes .net in c# is a very interesting thing i especiall like the system.diagnostics when combined with string you can get the web browser's page source and open it in notepad like ie. even thiugh there are many flaw in ie it is a decent browser. I especially like building browsers in vb as i can use system diagnostics without having to call reference to it plus i can write html code on the fly much easier which allows me to display the source in a new tab anyways glad you liked the email app if you like you tube you can check out the you tube downloader that i have built at Downloading Youtube Videos C# WinForm Also i would very much like to see how the email app looks now that you have fixed it up. Is there somewhere i can download it or maybe email it to me at mrme60@gmail.com thanks again
GeneralHmm.. Very nice, but it's not workingmemberjohnstunsky2 Jun '10 - 0:01 
at least not with gmail....
I've entered details and nothing happened..
edit:
I get sending failure...
GeneralRe: Hmm.. Very nice, but it's not workingmembercharles henington2 Jun '10 - 0:25 
which are you using the vb or c# program? are you adding @gmail.com?
GeneralRe: Hmm.. Very nice, but it's not workingmemberjohnstunsky2 Jun '10 - 22:10 
c#
@gmail was added in from row...
GeneralRe: Hmm.. Very nice, but it's not workingmembercharles henington3 Jun '10 - 12:10 
I'm Sorry im not sure I quite understand what your saying. Are you saying that the program automatically added @gmail.com? I do not have it configured as such if you are expecting it to you could change the code a little and put something like (!(textbox1.EndsWith ("@gmail.com"))); (this.new mailaddress = textbox1.text + "@gmail.com"; This is not an exact code just off the top of my head I can try it out and let you know what i come up with but for now you will need to manually add the @gmail.com
GeneralRe: Hmm.. Very nice, but it's not workingmembercharles henington3 Jun '10 - 12:23 
I just checked it out and everything seems to be working fine here. Do you .net 3.5? this is what it is configured for if not try downloading the update and try again I will try to build it with another compiler and changing it up to include the add attachment form to the same form so that i can compile it that way and we will see if that works for you. but first do you have the gmail check box checked? and have you changed the port #? try port 465 it is currently set up for port 587 also if you go through a proxy that may also be the problem, not sure though dont use proxy's but if you have a way to turn the proxy off for a moment try doing that as well let me know how it works for you and ill try a differnt compile method good luck friend
GeneralMy vote of 1membermuellerh26 May '10 - 22:31 
Absolutly nothing new in this article - you described the standard way of sending emails via smtp like in many other documentations...
GeneralRe: My vote of 1membercharles henington27 May '10 - 13:26 
In all due respect I do not see many tutorials that show how to send from yahoo or live (also known as hotmail). Most posts that you come across for yahoo will tell you that it is not possible because yahoo does not support free accounts which in my tutorial i have given a good example of how to send mail via smtp with free yahoo account. It does not show how to use yahoo premium because i do not have a premium account to test on. Also most posts will say that it is not possible with live/hotmail accounts due to the fact that live/hotmail uses html based email only which again I have given a great example of how to send email via live/hotmail account. I will agree that there are many posts on how to send email with gmail as gmail is one of the most well documented email clients but i could not write a tutorial on sending email via smtp and not include gmail. Aol I do not know much about the online documentation on this email client as I wrote the Aol code purely by luck with out studying any documentation. Please Download one of my examples and try it out and you will see just how easy it is to send email with these smtp clients!
AnswerRe: My vote of 1membermuellerh27 May '10 - 20:38 
All I can see is, that you using simple SMTP-Servers (yahoo, google or whatever you want). There is nothing special from using other SMTP-Servers.
 
> Please Download one of my examples and try it out and you will see
> just how easy it is to send email with these smtp clients!
I use SMTP-Servers in my applications all day and since many years - using SMTP is the standard way sending EMails not only in .NET. Servernames for servers like yahoo, google etc. are easy to find in the Internet... All what you have described (except the servernames) I can also find in msdn/library with two clicks.
GeneralRe: My vote of 1membercharles henington27 May '10 - 23:03 
Maybe your right and maybe your wrong. You know how to use smtp then good for you then obviously this tutorial isnt for you i could care less if you think the tutorial is nothing new because to some people who are just learning .net, C#, or VB maybe this is what they are looking for and maybe not but i want to hear from people who are looking to learn something new. So if the tutorial is not anything new to you keep your opinion to yourself and maybe try helping the new people learn more on the subject. If your going to leave an opinion then make one that is going to build on a tutorial not show your ignorance.
GeneralRe: My vote of 1memberdaveauld8 Sep '10 - 19:29 
I respect your opinion, however not everyone has the same level of knowledge as yourself, and maybe just starting out their programming adventure.
 
Why else would there regularly be questions in the forums and Q&A section on how to send email. If it wasn't for the basics being presented in the articles, then the beginners would never move on.
Dave
 
Please support my CPRepWatcher article in the August competition!
 
Find Me On: Web|Facebook|Twitter|LinkedIn

GeneralMy vote of 1membermail-2226 May '10 - 20:40 
nothing new
GeneralRe: My vote of 1membercharles henington27 May '10 - 13:25 
In all due respect I do not see many tutorials that show how to send from yahoo or live (also known as hotmail). Most posts that you come across for yahoo will tell you that it is not possible because yahoo does not support free accounts which in my tutorial i have given a good example of how to send mail via smtp with free yahoo account. It does not show how to use yahoo premium because i do not have a premium account to test on. Also most posts will say that it is not possible with live/hotmail accounts due to the fact that live/hotmail uses html based email only which again I have given a great example of how to send email via live/hotmail account. I will agree that there are many posts on how to send email with gmail as gmail is one of the most well documented email clients but i could not write a tutorial on sending email via smtp and not include gmail. Aol I do not know much about the online documentation on this email client as I wrote the Aol code purely by luck with out studying any documentation. Please Download one of my examples and try it out and you will see just how easy it is to send email with these smtp clients.
GeneralCode formattingmemberspencepk12 May '10 - 9:28 
I know this probably has nothing to do with you, but the lack of code formatting; i.e. indenting,etc., makes the content of this post rather difficult to read.
GeneralRe: Code formattingmembercharles henington27 May '10 - 13:37 
I have attempted to correct the formatting issues so that it is not as difficult to read. Also, I have included the source code in C# and in VB if you would like to check them out and let me know what you think of my program. Thank you for your comment and let me know if there is anything I can do to make the content easier for you to read or any corrections you may find.
GeneralMy vote of 1memberYahia Alhami9 May '10 - 3:02 
nothing new

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 27 May 2010
Article Copyright 2010 by charles henington
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid