Click here to Skip to main content
15,867,834 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 598.7K   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

 
QuestionRecieved Mail in Vb.net Application Pin
Vrahmdev Tiwari29-Dec-16 20:34
Vrahmdev Tiwari29-Dec-16 20:34 
QuestionMy vote 4 Pin
Appie van Zon7-Nov-16 23:36
Appie van Zon7-Nov-16 23:36 
QuestionAbout sending message through VB.NET Pin
Member 1228360610-Feb-16 17:07
Member 1228360610-Feb-16 17:07 
QuestionGood Job. Need Little Help. Pin
Bhavesh Chudasama29-Jul-15 20:15
Bhavesh Chudasama29-Jul-15 20:15 
Questionplease help me Pin
Member 1140043225-Jan-15 3:57
Member 1140043225-Jan-15 3:57 
QuestionThe SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at Pin
surinderrawat16-Oct-14 23:44
surinderrawat16-Oct-14 23:44 
AnswerRe: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at Pin
Member 1118682029-Oct-14 5:50
Member 1118682029-Oct-14 5:50 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun28-Aug-14 18:46
Humayun Kabir Mamun28-Aug-14 18:46 
GeneralMy vote of 5 Pin
_Vitor Garcia_26-Mar-13 7:55
_Vitor Garcia_26-Mar-13 7:55 
Thank you Abhishek Sur ! Ty
GeneralMy vote of 5 Pin
rctaubert25-Aug-12 3:19
rctaubert25-Aug-12 3:19 
GeneralMy vote of 4 Pin
Merlin Brasil13-Aug-12 9:19
Merlin Brasil13-Aug-12 9:19 
QuestionThe remote certificate is invalid according to the validation procedure Pin
hulinning13-Aug-12 1:41
hulinning13-Aug-12 1:41 
QuestionNeed Help !!! This code is not working for me Pin
rocksean308-Aug-12 22:04
rocksean308-Aug-12 22:04 
AnswerRe: Need Help !!! This code is not working for me Pin
Abhishek Sur9-Aug-12 12:56
professionalAbhishek Sur9-Aug-12 12:56 
GeneralRe: Need Help !!! This code is not working for me Pin
rocksean3023-Aug-12 22:33
rocksean3023-Aug-12 22:33 
SuggestionThe size of latest update scared me !! :O Pin
rocksean308-Aug-12 21:35
rocksean308-Aug-12 21:35 
Generalmy vote of 5 Pin
bolivankit5-Jun-12 23:04
bolivankit5-Jun-12 23:04 
QuestionRefusal to send from my machine Pin
a_annunz19-Feb-12 0:49
a_annunz19-Feb-12 0:49 
Questionrequest to add toolbar Pin
jyothi asipu30-Jan-12 15:14
jyothi asipu30-Jan-12 15:14 
GeneralMy vote of 5 Pin
chandrashekhar racharla19-Jan-12 19:45
chandrashekhar racharla19-Jan-12 19:45 
Generalmy vote of "5" Pin
shaheen_mix7-Jan-12 1:22
shaheen_mix7-Jan-12 1:22 
GeneralMy vote of 5 Pin
UrvishSuthar1-Jan-12 6:51
UrvishSuthar1-Jan-12 6:51 
QuestionYou May Find This Interesting Too... Pin
shahabdhk23-Dec-11 10:21
shahabdhk23-Dec-11 10:21 
QuestionEmbed the image without using HTML Pin
ewics15-Aug-11 2:00
ewics15-Aug-11 2:00 
AnswerRe: Embed the image without using HTML Pin
Abhishek Sur15-Aug-11 7:06
professionalAbhishek Sur15-Aug-11 7:06 

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.