Send Email From C# Windows Application Using Gmail SMTP

In this article I will explain how to send email from a C# Windows application with attachment using Gmail SMTP.

Introduction

In this article we will see how to send email from a C# Windows Forms (WinForms) application with an attachment using Gmail SMTP. For this first we will design the interface for sending email and then we will set SMTP details of a Gmail account using the SmtpClient class.

Step 1

Create a Windows Application project and arrange the controls as in the following figure:

Send-Email-Windows-application-using-Gmail-SMTP.jpg

Step 2

Import the following namespaces:

using System.Net;

using System.Net.Mail;

Declare the following variable inside the class declaration:

MailMessage message;
SmtpClient smtp;


Write the following code in the btnSend_Click event:

 

try

{

    btnSend.Enabled = false;

    btnCancel.Visible = true;

    message = new MailMessage();

 

    if (IsValidEmail(txtTo.Text))

    {

        message.To.Add(txtTo.Text);

    }

 

    if (IsValidEmail(txtCC.Text))

    {

        message.CC.Add(txtCC.Text);

    }

    message.Subject = txtSubject.Text;

    message.From = new MailAddress("[email protected]");

    message.Body = txtBody.Text;

    if (lblAttachment.Text.Length > 0)

    {

        if (System.IO.File.Exists(lblAttachment.Text))

        {

            message.Attachments.Add(new Attachment(lblAttachment.Text));

        }

    }

 

    // set smtp details

    smtp = new SmtpClient("smtp.gmail.com");

    smtp.Port = 25;

    smtp.EnableSsl = true;

    smtp.Credentials = new NetworkCredential("[email protected]", "********");

    smtp.SendAsync(message, message.Subject);

    smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);

}

catch (Exception ex)

{

    MessageBox.Show(ex.Message);

    btnCancel.Visible = false;

    btnSend.Enabled = true;

}

The MailMessage class includes all the details of the Email to be sent. So, first an instance of this class is created and its properties are set. The MailMessage.To.Add method is used to add the email address of the recipient of the mail. The MailMessage.CC.Add method is used to add a carbon copy recipient of the email. Multiple email addresses can be added in both of these Add methods either by a comma separated string value or by a collection objects. MailMessage.Subject property is used to get or set the subject of the email. MailMessage.From property is used to get or set From address of the email. MailMessage.Body property is used to get or set the email body. The MailMessage.Attachment.Add method is used to add attachment files to the email. It takes an Attachment collection as a parameter.

The IsValidEmail() function is used to check for valid email addresses. It just checks whether an email address has "@" and "." characters in it. This function can be improved using Regex expressions.

The SmtpClient class is used to set SMTP details to send the email. It takes the host's name or its IP address. It is set to "smtp.gmail.com" because we are going to use Gmail SMTP to send our email. SmtpClient.Port is used to get or set the port number used for this SMTP. It is set to "25", which is the Gmail SMTP port. It is also the default SMTP port. SmtpClient.EnableSsl is used to specify whether this SmtpClient uses SSL to encrypt connection. Gmail uses SSL, so you must set its value to true otherwise you will get a System.Net.Mail.SmtpException exception with the following error message:

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. bf6sm2271471pab.3"

SmtpClient.Credentials is used to get or set user id and password for SMTP sender. The SmtpClient.SendAsync() method sends the email using a background thread. It does not block the user interface. It takes two parameters, MailMessage and a UserToken. MailMessage contains all the email details and UserToken is an object you want to send with the email which you can get in SendCompleted event using e.UserState property. The SendCompleted event is fired when an asynchronous email send operation completes. The email send can be cancelled using the SendAsyncCancel() method or an error occurs.

Step 3

Write the following code for SendCompleted, btnCancel_Click and lnkAttachFile_LinkClicked events:

 

void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)

{

    if (e.Cancelled==true)

    {

        MessageBox.Show("Email sending cancelled!");

    }

    else if (e.Error != null)

    {

        MessageBox.Show(e.Error.Message);

    }

    else

    {

        MessageBox.Show("Email sent sucessfully!");

    }

   

    btnCancel.Visible = false;

    btnSend.Enabled = true;

}

 

private void btnCancel_Click(object sender, EventArgs e)

{

    smtp.SendAsyncCancel();

    MessageBox.Show("Email sending cancelled!");

}

 

SmtpClient.SendAsyncCancel() method is used to cancel the email send operation.

 

private void lnkAttachFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{

    if (openFileDialog1.ShowDialog() != DialogResult.Cancel)

    {

        lblAttachment.Text = openFileDialog1.FileName;

        lblAttachment.Visible = true;

        lnkAttachFile.Visible = false;

    }

}

An OpenFileDialog is used to select an attachment file.
 


Similar Articles