Header Ads

Send email with Attachment using Windows Application (Windows Forms) in C# and VB.Net

Multiple attachments will be attached to the Email from Folder (Directory) using the OpenFileDialog control.



This article will illustrate how to send email in Windows Application (Windows Forms) using GMAIL SMTP server, C# and VB.Net.


In this article I will explain with an example, how to send email with multiple attachments using Windows Application (Windows Forms) in C# and VB.Net.
Multiple attachments will be attached to the Email from Folder (Directory) using the OpenFileDialog control.
This article will illustrate how to send email in Windows Application (Windows Forms) using GMAIL SMTP server, C# and VB.Net.
Form Controls
The following Form consists of TextBox, Multiline TextBox, LinkLabel and OpenFileDialog controls which are used to capture the details of the Email to be send.
There is also a Button which when clicked, the email will be sent.
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Net.Mail;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Attaching Files to email using OpenFileDialog control
When the Attach LinkLabel is clicked, it opens the OpenFileDialog control for selecting files to be attached.
Once the Files are selected and OK Button of the Dialog is clicked, a loop is executed over the selected files and the names of the selected files are displayed in a Label.
C#
private void lnkAttachment_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    foreach (string filePath in openFileDialog1.FileNames)
    {
        if (File.Exists(filePath))
        {
            string fileName = Path.GetFileName(filePath);
            lblAttachments.Text += fileName + Environment.NewLine;
        }
    }
}
VB.Net
Private Sub lnkAttachment_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgsHandles lnkAttachment.LinkClicked
    openFileDialog1.ShowDialog()
End Sub
Private Sub openFileDialog1_FileOk(sender As System.Object, e As System.ComponentModel.CancelEventArgsHandles openFileDialog1.FileOk
    For Each filePath As String In openFileDialog1.FileNames
        If File.Exists(filePath) Then
            Dim fileName As String = Path.GetFileName(filePath)
            lblAttachments.Text += fileName + Environment.NewLine
        End If
    Next
End Sub
Sending Email with Attachment using Gmail SMTP
When the Send button is clicked, the values of the Sender email address (From), Recipient email address (To), Subject and Body are read from the respective TextBoxes.
Then all these values are set into an object of the MailMessage class.
Then an object of SmtpClient class is created and the settings of the GMAIL SMTP server i.e. Host, Username, Password and Port are set.
NoteIt is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.
Finally the email is sent using the Send function of the SmtpClient class object.
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.
SmptClient Class Properties
Following are the properties of the SmtpClient 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 the Account used to send emails.
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).
Port – Port Number of the SMTP server (Gmail: 587).
C#
private void btnSend_Click(object sender, EventArgs e)
{
    using (MailMessage mm = new MailMessage(txtEmail.Text.Trim(), txtTo.Text.Trim()))
    {
        mm.Subject = txtSubject.Text;
        mm.Body = txtBody.Text;
        foreach (string filePath in openFileDialog1.FileNames)
        {
            if (File.Exists(filePath))
            {
                string fileName = Path.GetFileName(filePath);
                mm.Attachments.Add(new Attachment(filePath));
            }
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text.Trim(), txtPassword.Text.Trim());
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        MessageBox.Show("Email sent.""Message");
    }
}
VB.Net
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgsHandles btnSend.Click
    Using mm As New MailMessage(txtEmail.Text.Trim(), txtTo.Text.Trim())
        mm.Subject = txtSubject.Text
        mm.Body = txtBody.Text
        For Each filePath As String In openFileDialog1.FileNames
            If File.Exists(filePath) Then
                Dim fileName As String = Path.GetFileName(filePath)
                mm.Attachments.Add(New Attachment(filePath))
            End If
        Next
        mm.IsBodyHtml = False
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential(txtEmail.Text.Trim(), txtPassword.Text.Trim())
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
        MessageBox.Show("Email sent.""Message")
    End Using
End Sub
Screenshots
The Form for sending email

Không có nhận xét nào

Được tạo bởi Blogger.