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

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.

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 port : 465 or 587
your account Name:###
your password:###

Lets Start Our Work

Step 1.
Add following Namespace

using System.Net.Mail; //Added for using MailMessage class
using System.Net; //Added for using NetworkCredential class
Create your smtp client

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

step 3.
Setup e-mail message

MailMessage message = new MailMessage();
message.To.Add(txtTo.Text); // Add Receiver mail Address message.From = new MailAddress(txtUsername.Text); // Sender address message.Subject = txtSubject.Text;
message.IsBodyHtml = true; //HTML email message.Body = txtBody.Text;

Attaching File to message

if (lstAttachedFiels.Items.Count > 0)
    Attachment a;
    foreach ( string s in lstAttachedFiels.Items)
        a = new Attachment(s);
        message.Attachments.Add(a);  //Adding attachment to message

Sending Mail


Ebook Download
View all
View all