Click here to Skip to main content
6,822,613 members and growing! (17,239 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Email     Intermediate License: The Code Project Open License (CPOL)

How to Send Mails from your GMAIL Account through VB.NET or C#. Windows Programming, with a Bit of Customization

By Abhishek Sur

Sending Mails from your Windows Application
C#, VB8.0, Windows, .NET2.0VS2005, Dev
Posted:18 Sep 2007
Updated:19 Mar 2008
Views:62,048
Bookmarked:126 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
44 votes for this article.
Popularity: 5.90 Rating: 3.59 out of 5
4 votes, 9.3%
1
2 votes, 4.7%
2
6 votes, 14.0%
3
8 votes, 18.6%
4
23 votes, 53.5%
5

Updates to Release 2

Introduction

It is a good way to use your Google mail client to send mails through your Windows Programs. Usually most of us who don't have their mailing hosts with them can use this simple code to make a program that could send mails to any SMTP Web hosts. I have made one and I want to share it with all of you. Please comment on how this could be made more attractive. Thanks a lot.

Background

For mastering this topic, it is recommended that you know some of the features of VB.NET so that you could go through the code. The program is for Windows application built in VB.NET. So you need ideas regarding VB.NET. Later on, I will post some other articles to allow this to be used from your Web application and also in C#.

Using the Code

If you are going through the codes, first I have included a namespace called System.Net.Mail so that I don't have to recall the full namespace path for creating objects of classes inside them. The first thing you need is to create an object of MailMessage class from this namespace. The name of my form is Mailform, so a reference to it is with regard to my own Windows form class. During form load, I have assigned a readonly textbox, which is a formtext box to my Gmail account address. This textbox will be used for sending mails. So here, you give your own mailing account address. Later on, I have created an object of SmtpClient class called SmtpServer. This object is used to send mails of my mailmessage with NetworkCredentials. If you have your own host, you don't need networkcredentials to be attached with SmtpServer.Credentials. Here, in the constructor, I have added my email address and my password, use your own, whenever you are creating your own application. Next, the portnumber, this is 587 for sending mails from Gmail. So you should explicitly use that. Another thing, whenever you are using Gmail, you need EnableSsl to be set to true, because Gmail needs secure authentication; smtpserver.send(mail) is actually sending mails.

Code Using VB.NET
//
// Simple application to send mails to any mail clients from Gmail account
// Using VB.NET
Imports System.Net.Mail
Public Class mailform
    Dim mail As New MailMessage()

   Private Sub mailform_Load(ByVal sender As System.Object, ByVal e As _
                System.EventArgs) Handles MyBase.Load
        TextBox2.Text = "xyz@gmail.com"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim SmtpServer As New SmtpClient()
        SmtpServer.Credentials = New Net.NetworkCredential
                    ("xyz@gmail.com", "password")
        SmtpServer.Port = 587
        SmtpServer.Host = "smtp.gmail.com"
        SmtpServer.EnableSsl = True

        mail = New MailMessage()
        Dim addr() As String = TextBox1.Text.Split(",")
        Try
            mail.From = New MailAddress("xyz@gmail.com",
                "Web Developers", System.Text.Encoding.UTF8)

            Dim i As Byte
            For i = 0 To addr.Length - 1
                mail.To.Add(addr(i))
            Next
            mail.Subject = TextBox3.Text
            mail.Body = TextBox4.Text
            If ListBox1.Items.Count <> 0 Then
                For i = 0 To ListBox1.Items.Count - 1
                    mail.Attachments.Add(New Attachment
                        (ListBox1.Items.Item(i)))
                Next
            End If
            mail.DeliveryNotificationOptions =
                    DeliveryNotificationOptions.OnFailure
            mail.ReplyTo = New MailAddress(TextBox1.Text)
            SmtpServer.Send(mail)
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ListBox1.Items.Add(OpenFileDialog1.FileName)
        End If
    End Sub
End Class
Code Using C#
//
// Simple application to send mails to any mail clients from Gmail account
// Using 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 Gmail
{
    public partial class Form1 : Form
    {
        String path;
        MailMessage mail = new MailMessage();
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential
                        ("xyz@gmail.com", "password");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            mail = new MailMessage();
            String[] addr = TextBox1.Text.Split(',');
            try
            {
                mail.From = new MailAddress("xyz@gmail.com",
                "Developers", System.Text.Encoding.UTF8);
                Byte i;
                for( i = 0;i< addr.Length; i++)
                    mail.To.Add(addr[i]);
                mail.Subject = TextBox3.Text;
                mail.Body = TextBox4.Text;
                if(ListBox1.Items.Count != 0)
                {
                    for(i = 0;i<ListBox1.Items.Count;i++)
          mail.Attachments.Add(new Attachment(ListBox1.Items[i].ToString()));
                }
          mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.ReplyTo = new MailAddress(TextBox1.Text);
                SmtpServer.Send(mail);
            }
            catch (Exception ex){
            MessageBox.Show(ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox2.Text = "xyz@gmail.com";
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if(OpenFileDialog1.ShowDialog()== DialogResult.OK)
            {
                ListBox1.Items.Add(OpenFileDialog1.FileName);
            }
        }
    }
} 

You need to change your userid from xyz@gmail.com to your own Gmail userid and password from "Password" to your own password.

Here is a snapshot of the Windows Form. Please check it out.

Screenshot - coolimage.jpg

Updates to Release 2

In this update, I am adding a few tricks so that you could embed an image within your Gmail client, and can easily send mails with your company logo. Just download the code from the links at the top of this article and follow it.

Code Using VB.NET
//Using VB.NET
Imports System.Net.Mail
Imports System.Net.Mime

Public Class mailform
    Dim path As String
    Dim mail As New MailMessage()
    Private Sub mailform_Disposed(ByVal sender As Object,
            ByVal e As System.EventArgs) Handles Me.Disposed
        End
    End Sub

    Private Sub mailform_Load(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox2.Text = "xyz@gmail.com"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button1.Click
        Dim SmtpServer As New SmtpClient()
        SmtpServer.Credentials = New Net.NetworkCredential("xyz@gmail.com",
                                "password")
        SmtpServer.Port = 587
        SmtpServer.Host = "smtp.gmail.com"
        SmtpServer.EnableSsl = True
        mail = New MailMessage()
        Dim addr() As String = TextBox1.Text.Split(",")
        Try
            mail.From = New MailAddress("xyz@gmail.com", "Developers",
                        System.Text.Encoding.UTF8)
            Dim i As Byte
            For i = 0 To addr.Length - 1
                mail.To.Add(addr(i))
            Next
            mail.Subject = TextBox3.Text
            'mail.Body = TextBox4.Text
            If ListBox1.Items.Count <> 0 Then
                For i = 0 To ListBox1.Items.Count - 1
                  mail.Attachments.Add(New Attachment(ListBox1.Items.Item(i)))
                Next
            End If
            Dim logo As New LinkedResource(path)
            logo.ContentId = "Logo"
            Dim htmlview As String
            htmlview = "<html><body><table border=2><tr width=100%><td>
        <img src=cid:Logo alt=companyname /></td>
        <td>MY COMPANY DESCRIPTION</td></tr></table>
                        <hr/></body></html>"
            Dim alternateView1 As AlternateView =
        AlternateView.CreateAlternateViewFromString(htmlview +
              TextBox4.Text, Nothing, MediaTypeNames.Text.Html)
            alternateView1.LinkedResources.Add(logo)
            mail.AlternateViews.Add(alternateView1)
            mail.IsBodyHtml = True
            mail.DeliveryNotificationOptions =
                DeliveryNotificationOptions.OnFailure
            mail.ReplyTo = New MailAddress(TextBox1.Text)
            SmtpServer.Send(mail)
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button2.Click
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ListBox1.Items.Add(OpenFileDialog1.FileName)
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button4.Click
        Dim d1 As New OpenFileDialog()
        If d1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            path = d1.FileName
            TextBox5.Text = d1.FileName
        End If
    End Sub
End Class
Code Using C#
//Using 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 Gmail
{
    public partial class Form1 : Form
    {
        String path;
        MailMessage mail = new MailMessage();
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            SmtpClient SmtpServer = new SmtpClient();
 SmtpServer.Credentials = new System.Net.NetworkCredential
                        ("xyz@gmail.com", "password");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            mail = new MailMessage();
            String[] addr = TextBox1.Text.Split(',');
            try
            {
                mail.From = new MailAddress("xyz@gmail.com",
                "Developers", System.Text.Encoding.UTF8);
                Byte i;
                for( i = 0;i< addr.Length; i++)
                    mail.To.Add(addr[i]);
                mail.Subject = TextBox3.Text;
                mail.Body = TextBox4.Text;
                if(ListBox1.Items.Count != 0)
                {
                    for(i = 0;i<ListBox1.Items.Count;i++)
                    mail.Attachments.Add(new Attachment(ListBox1.Items[i].ToString()));
                }
                LinkedResource logo = new LinkedResource(path);
                logo.ContentId = "Logo";
                string htmlview;
 htmlview = "<html><body><table border=2><tr width=100%><td>
    <img src=cid:Logo alt=companyname /></td><td>MY COMPANY DESCRIPTION
                </td></tr></table><hr/></body></html>";
 AlternateView alternateView1 = AlternateView.CreateAlternateViewFromString
           (htmlview + TextBox4.Text, null, MediaTypeNames.Text.Html);
                alternateView1.LinkedResources.Add(logo);
                mail.AlternateViews.Add(alternateView1);
                mail.IsBodyHtml = true;
 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.ReplyTo = new MailAddress(TextBox1.Text);
                SmtpServer.Send(mail);
            }
            catch (Exception ex){
            MessageBox.Show(ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox2.Text = "xyz@gmail.com";
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if(OpenFileDialog1.ShowDialog()== DialogResult.OK)
            {
                ListBox1.Items.Add(OpenFileDialog1.FileName);
            }
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog d1 = new OpenFileDialog();
             if(d1.ShowDialog() == DialogResult.OK)
             {
                path = d1.FileName;
                TextBox5.Text = d1.FileName;
            }
        }
    }
} 

Here in this code, I am using HTML to send my mail rather than sending plain text format, so that I can embed an image within the mail message. Well, to send HTML formatted mail message, I have used MediaTypeNames.Text.Html in the CreateAlternateViewFromString. This alternate view class is used to format a view of email message in the Web client. This formatted view can be Text, HTML, XML, RichText etc. I am using HTML here. In my htmlview string variable, I have made the initial logo that is to be shown. The linkedResource class constructor takes one file path, that is taken from another OpenFileDialog box. This will create a linked resource just within the body of the email message. Thus, I have used this feature to link an image resource shown to my client through HTML. In my HTML, I have used the same contentId which is here "logo" by writing cid:Logo which references to the image file linked to the mailmessage. Now see the snapshot below:

Screenshot - coolimage2.jpg

After sending the message, it will look like:

Screenshot - coolimage3.jpg

Just check it. Using embedded image within your mail message will enable you to see those images while you are offline from outlook or any email client because this logo will be cached normally.

I think this modification could help you.

Update 3

In this update, I have included some customization to the application. I have taken some of the specified values to the Registry. I didn't include Cryptography here, so that it could be easier for the naive to understand. For advanced users who want to use my software, I will definitely release one which includes all the security measures.

//Login Form
public partial class Login : Form
    {
        private string userid;
        private string password;
        private RegistryKey hklmu;
        private RegistryKey hklmp;

        public string UserID
        {
            get
            {
                userid = hklmu.GetValue("uid").ToString();
                return userid;
            }
            set
            {

                hklmu.SetValue("uid", value.ToString());
                userid = value;
            }
        }
        public string Password
        {
            get
            {
                password  = hklmp.GetValue("passwd").ToString();
                return password;
            }
            set
            {

                hklmp.SetValue("passwd", value.ToString());
                password = value;
            }
        }

        public Login()
        {
            InitializeComponent();
            hklmu = Registry.LocalMachine;
            hklmp = Registry.LocalMachine;
            hklmp = hklmp.OpenSubKey("SOFTWARE\\GmailClient",true);
            hklmu = hklmu.OpenSubKey("SOFTWARE\\GmailClient",true);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.UserID = textBox1.Text;
            this.Password = textBox2.Text;
            this.Hide();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            textBox1.Text = this.UserID;
            textBox2.Text = this.Password;
        }

//Preview Form
public partial class Preview : Form
    {
        private string _document;

        public string Document
        {
            get { return _document; }
            set { _document = value; }
        }

        public Preview()
        {
            InitializeComponent();
        }

        private void Preview_Load(object sender, EventArgs e)
        {
            this.webBrowser1.DocumentText = this.Document;

        }
    }

//Save background Profile Info
public partial class ChangeProfile : Form
    {
        private RegistryKey hklm;
        public ChangeProfile()
        {
            InitializeComponent();
            hklm = Registry.LocalMachine;
            hklm = hklm.OpenSubKey("SOFTWARE\\GmailClient", true);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            hklm.SetValue("name", textBox1.Text);
            hklm.SetValue("address", textBox2.Text);
            hklm.SetValue("ph", textBox3.Text);
            hklm.SetValue("work", textBox4.Text);
            hklm.SetValue("quote", textBox6.Text);
            hklm.SetValue("website", textBox5.Text);
            this.Dispose();
        }

        private void ChangeProfile_Load(object sender, EventArgs e)
        {
            textBox1.Text = hklm.GetValue("name").ToString();
            textBox2.Text = hklm.GetValue("address").ToString();
            textBox3.Text = hklm.GetValue("ph").ToString();
            textBox4.Text = hklm.GetValue("work").ToString();
            textBox6.Text = hklm.GetValue("website").ToString();
            textBox5.Text = hklm.GetValue("quote").ToString();
        }
    }

Some of the pictures are shown below:

coolimageupdate1.JPG

coolimageupdate2.JPG

coolimageupdate3.JPG

You can see... those are accessories included in my project to help you work from the interface itself.

Hope to get good feedback from you. Thanks.

Points of Interest

Nothing. Just go through it, and may be something will happen next.

History

  • Release 1: This is my first release of this code. Please let me know what the network credentials are that could send mails to other mail clients, like Yahoo,Hotmail etc. Hoping to get some good responses.
  • Release 2: In this release, I have added another useful feature, so that you can send an embedded image from your Gmail account; very useful to send your company logo. This image is an embedded resource and will be cached with your email text. Check out my new release. It works.
  • Release 3: In this release, I have modified the article by adding the same code in C# So that C# programmers will also get the benefit from this code block.
  • Release 4: In this release I have made some profile related modifications.

Thanks a lot to everybody. Hope this could help you. Happy programming!

License

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

About the Author

Abhishek Sur


Member
The guy is doing programming since 2001. Started his career with C, then C++ and so on. He completed his Masters in Computers from JIS, Kolkata. He likes to know the unknown. Now he is doing job as .NET Developer in a MNC. If you want to add him as buddy... Just click here... Or Directly Send Messages

To email abhi2434@yahoo.com
He is now working in a US Based Company in Kolkata.

His WebSite
Home page

Technical Blog
Programming Help and Tricks
Hidden Tips on Windows
.NET Ideas(My Previous Blog)

Most Importantly, He uses Orkut very often add him if you want

If you like this, Try reading some more:
Articles Listing
Description never ends, lots of secret with him. Make him your friend to learn more.

Dont forget to vote or share your comments about his Writing

Thanks in advance.
Occupation: Web Developer
Company: Buildfusion Inc
Location: India India

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 70 (Total in Forum: 70) (Refresh)FirstPrevNext
GeneralUnable to connect to the remote server Pinmemberrubeesh201022:38 22 Jan '10  
GeneralRe: Unable to connect to the remote server PinmvpAbhishek Sur23:48 24 Jan '10  
GeneralRe: Unable to connect to the remote server Pinmemberrubeesh20101:08 25 Jan '10  
GeneralNice Code Pinmemberthatraja22:49 15 Jan '10  
GeneralRe: Nice Code PinmvpAbhishek Sur22:06 24 Jan '10  
QuestionHow can i send html enabled mail Pinmembermuhammadjamilkhan1:45 20 Dec '09  
AnswerRe: How can i send html enabled mail PinassociateAbhishek Sur22:16 20 Dec '09  
GeneralNice PinmemberKasautiii23:00 30 Oct '09  
GeneralRe: Nice PinassociateAbhishek Sur8:36 31 Oct '09  
Generalhow to embed the linked resources and alternative view PinmemberJalal Hussain Baig21:48 19 Oct '09  
GeneralRe: how to embed the linked resources and alternative view PinassociateAbhishek Sur9:00 30 Oct '09  
GeneralRe Pinmembershoaibxavi21:56 8 Sep '09  
GeneralRe: Re PinassociateAbhishek Sur23:21 8 Sep '09  
GeneralExcellent Job PinmemberS G 19861:03 23 Jun '09  
GeneralRe: Excellent Job PinmemberAbhishek Sur23:46 23 Jun '09  
NewsYou left out a bunch of things Pinmemberken.tachyon12:16 19 Jun '09  
GeneralRe: You left out a bunch of things PinmemberAbhishek Sur23:17 21 Jun '09  
GeneralE-mail code project ...... Pinmembervladkara8:29 5 May '09  
GeneralRe: E-mail code project ...... PinmemberAbhishek Sur22:39 6 May '09  
QuestionProblems with proxy... Pinmemberkennyomar11:21 29 Dec '08  
GeneralUnable to connect remote server PinmemberMember 136072520:57 29 Nov '08  
GeneralRe: Unable to connect remote server PinmemberAbhishek Sur21:30 9 Dec '08  
GeneralMail send Error Pinmemberhoducduy18:02 2 Nov '08  
GeneralRe: Mail send Error PinmemberAbhishek Sur3:55 3 Nov '08  
Generalsmtp connection by proxy?? Pinmemberrazohad18:47 28 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 19 Mar 2008
Editor: Deeksha Shenoy
Copyright 2007 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project