In this article I will explain with an example, how to send email using Windows Application (Windows Forms) in C# and VB.Net.
Form Design
The following Form consists of:
TextBox – For capturing the values of Recipient
Email address, Subject, Body,
Gmail account email address,
Gmail account password.
OpenFileDialog – For attaching file as attachment to the email.
LinkLabel – For opening OpenFileDialog.
The LinkLabel has been assigned with the following event:
LinkClicked – This event is triggered when LinkLabel is clicked.
Button – For sending email.
The Button has been assigned with the Click event handler.
Mail Server Settings in App.Config file
The following Mail Server settings need to be saved in the
App.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Configuration
Imports System.Net.Configuration
Attaching File as attachment to the email
When the LinkLabel is clicked, the OpenFileDialog control will be opened for selecting file to be attached.
Once the file is selected and OK Button of the Dialog is clicked, the name of the selected file is displayed in the
Label control.
C#
private void lnkAttachment_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
if (File.Exists(filePath))
{
string fileName = Path.GetFileName(filePath);
lblAttachment.Text = fileName;
}
}
VB.Net
Private Sub lnkAttachment_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkAttachment.LinkClicked
openFileDialog1.ShowDialog()
End Sub
Private Sub openFileDialog1_FileOk(sender As Object, e As CancelEventArgs) Handles openFileDialog1.FileOk
Dim filePath As String = openFileDialog1.FileName
If File.Exists(filePath)Then
Dim fileName As String = Path.GetFileName(filePath)
lblAttachment.Text = fileName
End If
End Sub
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address
To – Recipient(s) Email Address
CC – Carbon Copies (if any)
BCC – Blind Carbon Copies (if any)
Subject – Subject of the Email
Body – Body of the Email
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of to Account used to send emails
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
Port – Port Number of the SMTP sever (Gmail: 587)
When the SendEmail Button is clicked, the Recipient email address (to), the Sender email address (from), Subject and Body values are fetched from their respective fields and are set into an object of the MailMessage class.
If the file is selected then, the file is added as attachment to the Attachments list of the MailMessage Object.
Then, an object of
SmtpClient class is created and the settings of the
GMAIL SMTP server i.e.
Host,
Port,
EnableSsl and
DefaultCredentials are fetched from the
AppSettings section of the
App.Config file are set.
Finally, the email is sent using the Send function of the SmtpClient class object and a success message is displayed using MessageBox class.
C#
private void btnSend_Click(object sender, EventArgs e)
{
string host = ConfigurationManager.AppSettings["Host"];
int port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
bool enableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
bool defaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["DefaultCredentials"]);
//Read SMTP section from App.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(txtEmail.Text,txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (!string.IsNullOrEmpty(openFileDialog1.FileName))
{
mm.Attachments.Add(new Attachment(openFileDialog1.FileName));
}
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = smtpSection.Network.Host;
smtp.Port = smtpSection.Network.Port;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
NetworkCredential networkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Send(mm);
MessageBox.Show("Email sent.", "Message");
}
}
}
VB.Net
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
Dim host As String = ConfigurationManager.AppSettings("Host")
Dim port As Integer = Convert.ToInt32(ConfigurationManager.AppSettings("port"))
Dim enableSsl As Boolean = Convert.ToBoolean(ConfigurationManager.AppSettings("EnableSsl"))
Dim defaultCredentials As Boolean = Convert.ToBoolean(ConfigurationManager.AppSettings("DefaultCredentials"))
'Read SMTP section from App.Config.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Using mm As New MailMessage(txtEmail.Text, txtTo.Text)
mm.Subject = txtSubject.Text
mm.Body = txtBody.Text
If Not String.IsNullOrEmpty(openFileDialog1.FileName)Then
mm.Attachments.Add(New Attachment(openFileDialog1.FileName))
End If
mm.IsBodyHtml = False
Using smtp As SmtpClient = New SmtpClient()
smtp.Host= smtpSection.Network.Host
smtp.Port = smtpSection.Network.Port
smtp.EnableSsl = smtpSection.Network.EnableSsl
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
Dim networkCred As NetworkCredential = New NetworkCredential(txtEmail.Text, txtPassword.Text)
smtp.Send(mm)
MessageBox.Show("Email sent." ,"Message")
End Using
End Using
End Sub
Screenshot
Email Form
Received Email
Downloads