Click here to Skip to main content
15,879,095 members
Articles / Programming Languages / Visual Basic

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

Rate me:
Please Sign up or sign in to vote.
4.12/5 (90 votes)
9 Aug 2012CPOL5 min read 599.8K   43.3K   220   137
Sending Mails from your Windows Application

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
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#
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
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#
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.

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

Sending_Emails_From_GMAIL/coolimageupdate1.jpg

Sending_Emails_From_GMAIL/coolimageupdate2.jpg

Sending_Emails_From_GMAIL/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)


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
GeneralMy vote of 5 Pin
dim13113-Jul-11 2:34
dim13113-Jul-11 2:34 
QuestionThanks... Pin
pradip rupareliya13-Jul-11 0:45
pradip rupareliya13-Jul-11 0:45 
GeneralMy vote of 5 Pin
anshumanpatil15064-May-11 19:02
anshumanpatil15064-May-11 19:02 
Generalhelp me out Pin
semekor10-Mar-11 0:42
semekor10-Mar-11 0:42 
Question....and How to receive Mails from My GMAIL Account through C#? Pin
Ronrocket15-Feb-11 5:28
Ronrocket15-Feb-11 5:28 
AnswerRe: ....and How to receive Mails from My GMAIL Account through C#? Pin
charles henington18-Apr-11 13:49
charles henington18-Apr-11 13:49 
GeneralNot Sending Mail in Port 465 Pin
Anubhava Dimri15-Feb-11 1:08
Anubhava Dimri15-Feb-11 1:08 
GeneralRe: Not Sending Mail in Port 465 Pin
charles henington18-Apr-11 13:44
charles henington18-Apr-11 13:44 
GeneralRe: Not Sending Mail in Port 465 Pin
Anubhava Dimri18-Apr-11 18:15
Anubhava Dimri18-Apr-11 18:15 
GeneralMy vote of 5 Pin
jmnemonik18-Jan-11 8:25
jmnemonik18-Jan-11 8:25 
QuestionError in seding mail... Pin
hardyhardy23-Dec-10 4:19
hardyhardy23-Dec-10 4:19 
AnswerRe: Error in seding mail... Pin
Abhishek Sur26-Dec-10 20:34
professionalAbhishek Sur26-Dec-10 20:34 
GeneralMy vote of 4 Pin
Libin Jose chemperi6-Dec-10 20:21
Libin Jose chemperi6-Dec-10 20:21 
QuestionNice article, how to simpley encrypt the sent mail [modified] Pin
ifEndIF16-Nov-10 0:14
ifEndIF16-Nov-10 0:14 
AnswerRe: Nice article, how to simpley encrypt the sent mail Pin
Abhishek Sur16-Nov-10 9:36
professionalAbhishek Sur16-Nov-10 9:36 
GeneralMy vote of 5 Pin
Smaaart5-Oct-10 19:09
Smaaart5-Oct-10 19:09 
GeneralMy vote of 5 Pin
ramsundar198728-Sep-10 0:36
ramsundar198728-Sep-10 0:36 
GeneralMy vote of 5 Pin
anwar6662-Aug-10 6:17
anwar6662-Aug-10 6:17 
GeneralHaven't heard from you Pin
charles henington31-May-10 23:47
charles henington31-May-10 23:47 
GeneralRe: Haven't heard from you Pin
Abhishek Sur1-Jun-10 0:41
professionalAbhishek Sur1-Jun-10 0:41 
QuestionHow about PROXY server Pin
alexxksys10-May-10 21:33
alexxksys10-May-10 21:33 
QuestionRe: How about PROXY server Pin
Lysander Charsi12-May-11 1:07
Lysander Charsi12-May-11 1:07 
Generalhi, very nice Pin
Mohammad Elsheimy8-May-10 2:08
Mohammad Elsheimy8-May-10 2:08 
GeneralJust wanted to let you know Pin
charles henington7-May-10 0:57
charles henington7-May-10 0:57 
GeneralRe: Just wanted to let you know Pin
Abhishek Sur20-Apr-11 9:03
professionalAbhishek Sur20-Apr-11 9:03 

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.