Sending Email using C# (with HTML body & Attachment )

Introduction

This article is provide a basic idea how we can send Emails from a C# Windows Application.
Here I have described how we can send mail with Attachment and HTML body.

Description
If we want to send mail then we need to know following things
1. SMTP Server address
2. Port No

Here I have used gmail as a SMTP Server
for gmail account
SMTP Server: smtp.gmail.com
SMTP port : 465 or 587
your account Name:###
your password:###

Lets Start Our Work

Step 1.
Add following Namespace

  1. using System.Net.Mail; //Added for using MailMessage class  
  2. using System.Net; //Added for using NetworkCredential class  

Step2.
Create your smtp client

  1. SmtpClient client = new SmtpClient();  
  2. client.Host = txtServer.Text; //Set your smtp host address  
  3. client.Port = int.Parse(txtPort.Text); // Set your smtp port address  
  4. client.DeliveryMethod = SmtpDeliveryMethod.Network;  
  5. client.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text); //account name and password  
  6. client.EnableSsl = true// Set SSL = true  

 

Step 3.
Setup e-mail message
  1. MailMessage message = new MailMessage();  
  2. message.To.Add(txtTo.Text); // Add Receiver mail Address  
  3. message.From = new MailAddress(txtUsername.Text); // Sender address  
  4. message.Subject = txtSubject.Text;  
  5.   
  6. message.IsBodyHtml = true//HTML email  
  7. message.Body = txtBody.Text;  

Attaching File to message

  1. if (lstAttachedFiels.Items.Count > 0)  
  2. {  
  3.     Attachment a;  
  4.     foreach ( string s in lstAttachedFiels.Items)  
  5.     {  
  6.         a = new Attachment(s);  
  7.         message.Attachments.Add(a);  //Adding attachment to message  
  8.     }  
  9. }  
Sending Mail 
  1. client.Send(message);