Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / Visual Basic

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

Rate me:
Please Sign up or sign in to vote.
4.57/5 (32 votes)
27 May 2010CPOL2 min read 151.7K   4.4K   92   31
Simple Email with Gmail, Yahoo, AOL, and Live mail via SMTP

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.

C#
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:

C#
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:

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

The above code should be changed to:

C#
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:

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

The above code should be changed to:

C#
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:

C#
SmtpClient SmtpServer = new SmtpClient();

and:

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

The code to be added is:

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

The final code to be added is:

C#
using System.Net;

License

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


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
QuestionAccess for less secure app->Turn On Pin
aazam rafiee zade18-Mar-15 3:15
aazam rafiee zade18-Mar-15 3:15 
QuestionGreat! Just what I was looking for Pin
gcode111-Apr-13 6:09
gcode111-Apr-13 6:09 
Questiondoes not work for LIVE Pin
zinxx8-Jan-13 2:25
zinxx8-Jan-13 2:25 
GeneralMy vote of 4 Pin
csharpbd19-Nov-12 20:24
professionalcsharpbd19-Nov-12 20:24 
Good but need more description...
GeneralMy vote of 1 Pin
ChewsHumans6-Feb-12 5:31
ChewsHumans6-Feb-12 5:31 
GeneralMy vote of 1 Pin
dvptUml16-Apr-11 23:48
dvptUml16-Apr-11 23:48 
GeneralMy vote of 1 Pin
Freax Domino30-Nov-10 10:54
Freax Domino30-Nov-10 10:54 
GeneralRe: My vote of 1 Pin
charles henington17-Mar-11 18:33
charles henington17-Mar-11 18:33 
Generalvery good article thanks but can't download the code Pin
Hasbi Allah22-Oct-10 6:35
Hasbi Allah22-Oct-10 6:35 
GeneralVery Good Pin
rspercy653-Jun-10 17:10
rspercy653-Jun-10 17:10 
GeneralRe: Very Good Pin
charles henington3-Jun-10 22:26
charles henington3-Jun-10 22:26 
GeneralHmm.. Very nice, but it's not working Pin
johnstunsky2-Jun-10 0:01
johnstunsky2-Jun-10 0:01 
GeneralRe: Hmm.. Very nice, but it's not working Pin
charles henington2-Jun-10 0:25
charles henington2-Jun-10 0:25 
GeneralRe: Hmm.. Very nice, but it's not working Pin
johnstunsky2-Jun-10 22:10
johnstunsky2-Jun-10 22:10 
GeneralRe: Hmm.. Very nice, but it's not working Pin
charles henington3-Jun-10 12:10
charles henington3-Jun-10 12:10 
GeneralRe: Hmm.. Very nice, but it's not working Pin
charles henington3-Jun-10 12:23
charles henington3-Jun-10 12:23 
GeneralMy vote of 1 Pin
nobodyxxxxx26-May-10 22:31
nobodyxxxxx26-May-10 22:31 
GeneralRe: My vote of 1 Pin
charles henington27-May-10 13:26
charles henington27-May-10 13:26 
AnswerRe: My vote of 1 Pin
nobodyxxxxx27-May-10 20:38
nobodyxxxxx27-May-10 20:38 
GeneralRe: My vote of 1 Pin
charles henington27-May-10 23:03
charles henington27-May-10 23:03 
GeneralRe: My vote of 1 Pin
DaveAuld8-Sep-10 19:29
professionalDaveAuld8-Sep-10 19:29 
GeneralMy vote of 1 Pin
mail-2226-May-10 20:40
mail-2226-May-10 20:40 
GeneralRe: My vote of 1 Pin
charles henington27-May-10 13:25
charles henington27-May-10 13:25 
GeneralCode formatting Pin
spencepk12-May-10 9:28
spencepk12-May-10 9:28 
GeneralRe: Code formatting Pin
charles henington27-May-10 13:37
charles henington27-May-10 13:37 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.