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#
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.
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
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 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:
After sending the message, it will look like:
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.
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;
}
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;
}
}
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:
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!