Sending Mail in C# using .Net Mail

Following self explanatory code snippets will demonstrate how to use .Net Mail to send Mail in C#. First of all, add “Using Directive” to .Net Mail and .Net Mime. The later one is for Mail attachment.


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


Let's start with SmtpClient. Here, I have created SmtpClient Object using my Gmail Account.


SmtpClient smtpServer = new SmtpClient();

smtpServer.Credentials = new System.Net.NetworkCredential("khan.rahim@gmail.com", "xxxxxx");
smtpServer.Port = 587;
smtpServer.Host = "smtp.gmail.com";
smtpServer.EnableSsl = true;

This following code snippet shows how to prepare your MailMessage.


MailMessage mailMessage = new MailMessage();

mailMessage.From = new MailAddress("khan.rahim@gmail.com", "A Rahim Khan", System.Text.Encoding.UTF8);
mailMessage.To.Add("rahim767@yahoo.com");

mailMessage.Subject = "Mail Using C# Code";
mailMessage.Body = "I have Used .Net Mail to send this Mail";

mailMessage.Attachments.Add(new Attachment("FILE PATH");

mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mailMessage.ReplyTo = new MailAddress("khan.rahim@gmail.com");

Finally, send your MailMessage by SmtpClient in this way.


smtpServer.Send(mailMessage);

To send Image Embedded HTML Mail in C#, you may have a look here.

Thanks
A Rahim Khan

Advertisements
  1. very good tutorial

    • shady Abdelaziz
    • June 9th, 2010

    I’m a beginner in C#
    and I want to make a C# Form with 3 ComboBox
    Connected at 3 Tables with stored procedure

    I want when select Item from CoboBox1 (say name)
    Retrieve at ComboBox2 (Company) of last selected item

    and when I select The last Company
    Retrieve at ComboBox3 all Departments at this company

    I was made the stored procedure but I want only the C# code to Link My form with the stored procedure

  2. Hey man, Thank you very much! I have been looking for this for quite some time! It’s very rare that you find a tutorial with this much depth and ease of use! Thank you so much, It worked perfectly!! :D

  3. I cannot thank you enough for the blog.Much thanks again. Keep writing.

  1. June 3rd, 2010
  2. April 11th, 2012

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: