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:

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.
Ahmad Al HalabiPosted Oct 3, 2023, 12:43 PM
Can i download it?
Yogeshjmc TailorPosted Jun 9, 2023, 8:35 AM
But my requirement is created web service this from & using project by service through is it possible
Yogeshjmc TailorPosted Jun 9, 2023, 8:34 AM
Dear Sir, I read your article and use this code also it working fine
Dharmendra Kumar PanditPosted Nov 27, 2019, 2:58 AM
Thank you sir... Nice article working fine
kalu singh raoPosted Jul 12, 2016, 8:06 AM
Nice...
Niket PatilPosted Mar 12, 2015, 3:03 AM
IsValidEmail its got error..... is asking generate method stub for IsValidEmail
Antony SmithPosted Feb 26, 2014, 7:23 AM
compiles fine but then I get the error: "The specified string is not in the form required for an e-mail address". Where is this error from in the code, and what form is it looking for, as the address is correct?
arjun singh chouhanPosted Aug 22, 2013, 4:55 AM
how to use in .aspnet
Digambar KadamPosted Oct 29, 2012, 1:16 AM
I have used this code but the error is "The method or Operation is not implemented" what is the solution of this error?
Digambar KadamPosted Oct 29, 2012, 1:16 AM
I have used this code but the error is "The method or Operation is not implemented" what is the solution of this error?
Anshika MittalPosted Oct 18, 2012, 11:28 PM
Great one...
dipali goelPosted Oct 18, 2012, 11:13 PM
thanx for sharing with us i was searching for it