Send Email with attachments from C# Windows application using Gmail SMTP

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

Introduction

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

Step 1:

Create a Windows Application project and arrange controls like following figure

Step:2

Import following namespaces

using System.Net;
using System.Net.Mail;

Declare following variable inside the class declaration

MailMessage message;
SmtpClient smtp;

Write following code in 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("deepak.sharma009@gmail.com");
     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("deepak.sharma009@gmail.com", "********");
     smtp.SendAsync(message, message.Subject);
     smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
     btnCancel.Visible = false;
     btnSend.Enabled = true;
}

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. MailMessage.To.Add method is used to add email of the recipient of the mail. MailMessage.CC.Add method is used to add 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 object. 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. MailMessage.Attachment.Add method is used to add attachment files to the email. It takes Attachment collection as parameter.

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

SmtpClient class is used to set SMTP details to send the email. It takes 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 Gmail SMTP port. It is also 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 System.Net.Mail.SmtpException exception with 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. 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. SendCompleted event is fired when an asynchronous email send operation completes, email send is cancelled using SendAsyncCancel() method or an error occurs.

Step:3

Write 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.

10 thoughts on “Send Email with attachments from C# Windows application using Gmail SMTP

  1. Lelala

    Will this code hang like the typical SMTPclient implementation when the server picks up the mail or is that stuff working asynchronous?
    Regards

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *