Click here to Skip to main content
Click here to Skip to main content

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

, 9 Aug 2012
Rate this:
Please Sign up or sign in to vote.
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
//
// 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:

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)

Share

About the Author

Abhishek Sur
Architect
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.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
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
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun28-Aug-14 18:46 
GeneralMy vote of 5 PinmemberVitorHugoGarcia26-Mar-13 7:55 
GeneralMy vote of 5 Pinmemberrctaubert25-Aug-12 3:19 
GeneralMy vote of 4 PinmemberMerlin Brasil13-Aug-12 9:19 
QuestionThe remote certificate is invalid according to the validation procedure Pinmemberlinhjob13-Aug-12 1:41 
Questionwelcome to: http://www.netetrader.com Pinmemberkuif8sa9s9-Aug-12 14:54 
QuestionNeed Help !!! This code is not working for me Pinmemberrocksean308-Aug-12 22:04 
AnswerRe: Need Help !!! This code is not working for me PinmemberAbhishek Sur9-Aug-12 12:56 
GeneralRe: Need Help !!! This code is not working for me Pinmemberrocksean3023-Aug-12 22:33 
SuggestionThe size of latest update scared me !! :O Pinmemberrocksean308-Aug-12 21:35 
Generalmy vote of 5 Pinmemberbolivankit5-Jun-12 23:04 
QuestionRefusal to send from my machine Pinmembera_annunz19-Feb-12 0:49 
Questionrequest to add toolbar [modified] Pinmemberjyothi asipu30-Jan-12 15:14 
GeneralMy vote of 5 Pinmemberchandrashekhar racharla19-Jan-12 19:45 
Generalmy vote of "5" Pinmembershaheen_mix7-Jan-12 1:22 
GeneralMy vote of 5 PinmemberURVISH SUTHAR from Ahmadabad Gujarat, India1-Jan-12 6:51 
QuestionYou May Find This Interesting Too... Pinmembershahabdhk23-Dec-11 10:21 
QuestionEmbed the image without using HTML Pinmemberewics15-Aug-11 2:00 
Hi,
Is there a way to embed an image to the email without using HTML tags. Because my email service provider removes the HTML part from the email!
AnswerRe: Embed the image without using HTML PinmvpAbhishek Sur15-Aug-11 7:06 
GeneralMy vote of 5 Pinmemberdim13113-Jul-11 2:34 
QuestionThanks... Pinmemberpradip rupareliya13-Jul-11 0:45 
GeneralMy vote of 5 Pinmemberanshumanpatil15064-May-11 19:02 
Generalhelp me out Pinmembersemekor10-Mar-11 0:42 
Question....and How to receive Mails from My GMAIL Account through C#? PinmemberRonrocket15-Feb-11 5:28 
AnswerRe: ....and How to receive Mails from My GMAIL Account through C#? Pinmembercharles henington18-Apr-11 13:49 

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 | Mobile
Web04 | 2.8.140827.1 | Last Updated 9 Aug 2012
Article Copyright 2007 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid