Click here to Skip to main content
11,566,437 members (50,530 online)
Click here to Skip to main content

Send E-Mail from your .NET Application using your GMail Account

, 24 May 2006 CPOL 384.9K 234
Rate this:
Please Sign up or sign in to vote.
Send E-Mail from your .NET application using your GMail Account
Sample Image - SendMailUsingGmailAccount.jpg

Introduction

Most independent developers like to include a message sending feature in their application. Well atleast I tried to... Of course it is not a problem for a user with a SMTP server access or a registered domain with a SMTP server access. But unfortunately I had neither of those. I use MSN, GMail and Yahoo for my mailing needs. Unfortunately Yahoo does not offer SMTP or POP access for its general/basic/free users. And MSN is not that reliable because I was expecting a lot of mails to be sent and received and as far as I know, they do not give you POP/SMTP access!

Typical Example You Will Find On the Internet

So I really hunted for a code segment that will help me use my free GMail account to send E-mail from my .NET account. Here is a complete reference library and FAQs regarding the System.Web.Mail namespace. And my code is basically different pieces joined together. Finally I met with success. Normally you will find thousands of sites offering the code below which has very little use, like:

  MailMessage mail = new MailMessage();
  mail.To = "xxxx@mailserver.com";
  mail.Bcc = "yyyy@mailserver.com; user3@mailserver.net";
  mail.From = "your email or name";
  mail.Subject = "your subject";
  mail.Body = "your subject";
  SmtpMail.SmtpServer = "10.4.1.2"; //your real server goes here or
  //you can add the address like "smtp.mailserver.com"
  SmtpMail.Send(mail);

Well most SMTP servers require authentication and sometimes SSL connection, so what then? The code above is USELESS. What are the things you need to add? There you go.

How to Use

Copy the above methods and paste in the Visual Studio IDE or any text editor you use. Add a reference to System.Web or System.Web.Mail DLL, change your account info like your mail address, password, etc. and enjoy.

Explanation of the Code

So what is happening in the example? Let's see:

Step 1: Create a mail msg object and assign the basic parts like From, To, Cc, Bcc, Subject, Body.

Step 2: Add some config settings in fields collection of the mailMessage object. The type of authentication we use is basic authentication and your user name, password, SMTP servers, port number that you will be using. For example: GMail username requires the full GMail address as username and you can use /connect to any of the ports.

//basic authentication
mailMsg.Fields.Add
    ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//sender email address
mailMsg.Fields.Add
    ("http://schemas.microsoft.com/cdo/configuration/sendusername", "myemail@gmail.com");
//plaintext password. 
//you can encrypt your password and keep in a config file 
//when you parse just decrypt it
mailMsg.Fields.Add
    ("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
// port number - smtp.gmail.com use port 465 or 587. use any one of them
// you can even make some grouping so different groups use different port 
// to share the load on server
mailMsg.Fields.Add
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); 

Step 3: This is the coolest and most important part that I spent a lot of time to discover.

mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); 
//Cool. Ha? Do not Change! 
//This part is a must if you want to access GMAIL's SMTP server

This line says/declares that your SMTP server requires SSL connection which is very much true/necessary for accessing to GMail's SMTP server.

Step 4: Assign the SMTP server name in System.Web.Mail.SmtpMail class's SMTP server object like:

SmtpMail.SmtpServer = "smtp.gmail.com";
You can also set the priority of your mail by:
// MailPriority is an enum. It has High, Low, Normal option
mailMsg.Priority = MailPriority.High;

Step 5: Call the send method of System.Web.Mail.SmtpMail. For example:

System.Web.Mail.SmtpMail.Send(myMailMsg);

.NET 2.0 Version

Some changes are required for .NET v2.0 as .NET 2.0 Mail is more organised and stable and has many extra features. So in the update, I am including .NET 2.0 version of my code.

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;
using System.Net.Mail;
using System.Net.Mime; 
//Mime is Not necerrary if you dont change the msgview and 
//if you dont add custom/extra headers 
using System.Threading;

namespace SendMailUsingGmail
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        static bool mailSent = false;

        public void SendMail()
        {
            //Builed The MSG
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add("reciver@gmail.com");
            msg.To.Add("another.reciver@yahoo.com");
            msg.From = new MailAddress(dummy@gmail.com, 
                "One Ghost",System.Text.Encoding.UTF8);
            msg.Subject = "Test mail using .net2.0";
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = "This is my msg Body";
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Priority = MailPriority.High;            
           
            //Add the Creddentials
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential
                ("dummy@gmail.com", "SecretPass");
            client.Port = 587;//or use 587            
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;
            client.SendCompleted += new SendCompletedEventHandler
                (client_SendCompleted);
            object userState=msg;
            try
            {
                //you can also call client.Send(msg)
                client.SendAsync(msg, userState);                
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                MessageBox.Show(ex.Message, "Send Mail Error");
            }
        }

        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MailMessage mail = (MailMessage)e.UserState;
            string subject = mail.Subject;

            if (e.Cancelled)
            {
                string cancelled = string.Format("[{0}] Send canceled.", subject);
                MessageBox.Show(cancelled);                
            }
            if (e.Error != null)
            {
                string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
                MessageBox.Show(error);                
            }
            else
            {
                MessageBox.Show("Message sent.");
            }
            mailSent = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.SendMail();
        }
    }
}

Limitation of this Code

This code may/may not work with .NET Framework v1.0 because the MailMessage object of .NETv1.0 does not have the MailMessage.Fields Collection. This was added in .NETv1.1. So it works fine with .NETv1.1 and v2.0.

Conclusion

The send method does not return anything. But you can add some mechanism (like a counter) to keep track of send message or even keep the return type of your method as a mailmessage type so that you can save to database for security reasons.

The reason I could not provide a complete send and receive example is because I am very busy with my thesis project. But I also wanted to publish the code sample on The Code Project as someone may find it helpful. I will publish a complete article about sending and receiving mail using GMail account from your Gmail account.

Future Upgrade Plan

I am planning to upload another complete article for both sending and receiving E-mail from GMail account from a single application with the complete source code. I need some feedback about which to choose, ASP.NET code or Windows programming sample or both? Moreover, I am going to add some config file to dynamically change mail settings like sender mail account, SMTP server name, default port number and priority, etc. Please send feedback to moshiur.m@gmail.com.

//This is fully working tested code. Copy and paste the code
//Edit some parts(UserName, password) and ENJOY!
public string sendMail (string from, string to, string cc, 
        string bcc, string subject, string body) {
    // Mail initialization
    MailMessage mailMsg = new MailMessage();
    mailMsg.From = from;
    mailMsg.To = to;
    mailMsg.Cc = cc;
    mailMsg.Bcc = bcc;
    mailMsg.Subject = subject;
    mailMsg.BodyFormat = MailFormat.Text;
    mailMsg.Body = body;
    mailMsg.Priority = MailPriority.High;
    // Smtp configuration
    SmtpMail.SmtpServer = "smtp.gmail.com";
    // - smtp.gmail.com use smtp authentication
    mailMsg.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
    mailMsg.Fields.Add(http://schemas.microsoft.com/cdo/configuration/sendusername, 
        "myemail@gmail.com");
    mailMsg.Fields.Add(http://schemas.microsoft.com/cdo/configuration/sendpassword, 
        "mypassword");
    // - smtp.gmail.com use port 465 or 587
    mailMsg.Fields.Add
        (http://schemas.microsoft.com/cdo/configuration/smtpserverport, "465");
    // - smtp.gmail.com use STARTTLS (some call this SSL)
    mailMsg.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
    // try to send Mail
    try 
    {
        SmtpMail.Send(mailMsg);
        return "";
    }
    catch (Exception ex) 
    {
        return ex.Message;
    }
}

License

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

Share

About the Author

Syed Moshiur Murshed
Software Developer Pöyry Infra GmbH
Austria Austria
I am Syed Moshiur Murshed from Bangladesh. I studied BSC in Computer Science at American International University Bangladesh(www.aiub.edu). And then MSC in Software Technology at Stuttgart University of Applied Science, Germany(www.hft-stuttgart.de). Currently I am employed as a Software Engineer at Pöyry Infra GmbH in Salzburg, Austria since 04-2011.
I have been learning C# for quite some time and Enjoying it.

You may also be interested in...

Comments and Discussions

 
QuestionSending Attached mail Pin
Member 1053742523-Jan-14 18:30
memberMember 1053742523-Jan-14 18:30 
GeneralSystem.Net.Mail Pin
oviis_4u4-Aug-10 8:47
memberoviis_4u4-Aug-10 8:47 
GeneralError With using System.Net.Mail.. Pin
oviis_4u3-Aug-10 12:44
memberoviis_4u3-Aug-10 12:44 
GeneralRe: Error With using System.Net.Mail.. Pin
Syed Moshiur Murshed4-Aug-10 8:03
memberSyed Moshiur Murshed4-Aug-10 8:03 
GeneralMy vote of 5 Pin
oviis_4u3-Aug-10 12:42
memberoviis_4u3-Aug-10 12:42 
GeneralRe: My vote of 5 Pin
Syed Moshiur Murshed4-Aug-10 8:01
memberSyed Moshiur Murshed4-Aug-10 8:01 
Questionwhere can i download the code to try ? Pin
haroldlai14-Apr-10 23:39
memberharoldlai14-Apr-10 23:39 
AnswerRe: where can i download the code to try ? Pin
Syed Moshiur Murshed15-Apr-10 8:06
memberSyed Moshiur Murshed15-Apr-10 8:06 
GeneralThe name 'InitializeComponent' does not eixst Pin
jcjohnso28-Mar-10 17:13
memberjcjohnso28-Mar-10 17:13 
GeneralProblem... Transport Error Pin
JRINC30-Nov-09 7:41
memberJRINC30-Nov-09 7:41 
Questionit can't work in a new a thread. Pin
leegool16-Sep-09 2:10
memberleegool16-Sep-09 2:10 
QuestionReally nice code , helped me out !! thanks - Can i use this code to mail 50+ persons at same time ? Pin
damon884-Aug-09 2:21
memberdamon884-Aug-09 2:21 
GeneralThank U !! Pin
athalyeakshay3-Aug-09 18:34
memberathalyeakshay3-Aug-09 18:34 
Generaldude thanx Pin
maheshsahini30-Mar-09 2:27
membermaheshsahini30-Mar-09 2:27 
GeneralThanks Pin
King Coffee4-Mar-09 15:05
memberKing Coffee4-Mar-09 15:05 
GeneralGeting Error Pin
madancode11-Jan-09 21:03
membermadancode11-Jan-09 21:03 
GeneralSending Mail Problem throw 465 Pin
eg_Anubhava2-Jan-09 1:09
membereg_Anubhava2-Jan-09 1:09 
GeneralRe: Sending Mail Problem throw 465 Pin
Syed Moshiur Murshed2-Jan-09 5:06
memberSyed Moshiur Murshed2-Jan-09 5:06 
GeneralThumbs Up Pin
Bilal Haider20-Dec-08 14:11
memberBilal Haider20-Dec-08 14:11 
GeneralSaving mail message in Drafts folder Pin
Chetan Sawant10-Nov-08 19:08
memberChetan Sawant10-Nov-08 19:08 
Generaldude, you rock!! Pin
greenknt7-Nov-08 9:14
membergreenknt7-Nov-08 9:14 
Generalgood work Pin
Amir Dabaghian25-Oct-08 20:52
memberAmir Dabaghian25-Oct-08 20:52 
GeneralNice code but how i send mail when server proxy is set. Pin
~Khatri Mitesh~21-Oct-08 2:48
member~Khatri Mitesh~21-Oct-08 2:48 
Generalhi there, nice code, what about... Pin
hesaigo999ca21-Aug-08 5:48
memberhesaigo999ca21-Aug-08 5:48 
Generalpretty good Pin
helloadj21-Jul-08 10:13
memberhelloadj21-Jul-08 10:13 
QuestionReceiving multiple times Pin
Saji S Nair18-Jul-08 15:51
memberSaji S Nair18-Jul-08 15:51 
Generalsound GREAT! Pin
doxuananh21-Jun-08 5:58
memberdoxuananh21-Jun-08 5:58 
GeneralIf you have trouble senind email using System.Net.Mail, try this Pin
magnusb9995-May-08 1:43
membermagnusb9995-May-08 1:43 
Generalgetting error Pin
Kishan Hathiwala20-Mar-08 7:58
memberKishan Hathiwala20-Mar-08 7:58 
GeneralThe remote certificate is invalid according to the validation procedure. Pin
Carmine_XX5-Mar-08 3:57
memberCarmine_XX5-Mar-08 3:57 
GeneralExcellent Article - Help needed to retreive email Pin
Anne Simmon4-Mar-08 23:59
memberAnne Simmon4-Mar-08 23:59 
GeneralThank Pin
m-chaos19-Feb-08 20:28
memberm-chaos19-Feb-08 20:28 
QuestionHow to retrieve email from .NET application by using Gmail account? Pin
Member 441721514-Feb-08 5:03
memberMember 441721514-Feb-08 5:03 
GeneralGood job! Pin
Coder_200713-Dec-07 20:05
memberCoder_200713-Dec-07 20:05 
Generalport 587!! Pin
gravz8427-Nov-07 20:00
membergravz8427-Nov-07 20:00 
Questionproblem!! Pin
dianlongliu23-Nov-07 15:54
memberdianlongliu23-Nov-07 15:54 
GeneralSending Mails with different "From Address" Pin
Mukesh Agarwal9-Oct-07 18:36
memberMukesh Agarwal9-Oct-07 18:36 
GeneralExcellent Article Pin
shaneiadt4-Oct-07 11:30
membershaneiadt4-Oct-07 11:30 
QuestionPort number Pin
cfricks3-Oct-07 9:59
membercfricks3-Oct-07 9:59 
AnswerRe: Port number Pin
tomascl26-Nov-07 8:11
membertomascl26-Nov-07 8:11 
GeneralI M GETTING THIS ERRO WHEN I M TRYING TO SEND MAIL Pin
bhavna patel1-Sep-07 22:11
memberbhavna patel1-Sep-07 22:11 
GeneralRe: I M GETTING THIS ERRO WHEN I M TRYING TO SEND MAIL Pin
Syed Moshiur Murshed2-Sep-07 18:59
memberSyed Moshiur Murshed2-Sep-07 18:59 
GeneralSending Mail + Multi Threading Pin
jorgetakeshita18-Aug-07 10:08
memberjorgetakeshita18-Aug-07 10:08 
Generalread e-mail from gmail Pin
techmind78625-Jul-07 21:44
membertechmind78625-Jul-07 21:44 
GeneralThe SMTP host was not found. Pin
usama999-Jul-07 4:26
memberusama999-Jul-07 4:26 
GeneralRe: The SMTP host was not found. Pin
newignasius17-Jul-07 18:43
membernewignasius17-Jul-07 18:43 
GeneralRe: The SMTP host was not found. Pin
Sajudeen Kassim31-Jul-07 22:31
memberSajudeen Kassim31-Jul-07 22:31 
GeneralRe: The SMTP host was not found. Pin
Sajudeen Kassim3-Aug-07 20:27
memberSajudeen Kassim3-Aug-07 20:27 
GeneralRe: The SMTP host was not found. Pin
kianoosh soorani24-Sep-07 22:02
memberkianoosh soorani24-Sep-07 22:02 
Questionpocket pc Pin
serkan31231-Jul-07 22:46
memberserkan31231-Jul-07 22:46 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 24 May 2006
Article Copyright 2006 by Syed Moshiur Murshed
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid