How to send emails using Gmail in C# and ASP.NET

Sending emails in your .NET applications requires right SMTP server configuration (it is Gmail in my case). I will use my Gmail address and password to succeed it.

First of all, you need to import corresponding libraries on the top of your code:

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

Then, use the code below by optimizing it as you wish how it is sent through your app.

// Email object
MailMessage mMailMessage = new MailMessage();

// Sender address
mMailMessage.From = new MailAddress("");

// Recepient address
mMailMessage.To.Add(new MailAddress(""));

// Bcc address
mMailMessage.Bcc.Add(new MailAddress(""));

// CC address
mMailMessage.CC.Add(new MailAddress(""));

// Subject
mMailMessage.Subject = "Test subject";

// Body
mMailMessage.Body = "Test message comes here<br><b>It supports HTML</b>";

string file = "C:\\testfile.xlsx";

// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);

// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);

// Add the file attachment to this e-mail message.

// Format of the mail message body
mMailMessage.IsBodyHtml = true;

// Priority
mMailMessage.Priority = MailPriority.Normal;

// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient("", 587)
    Credentials = new NetworkCredential("", "yourpassword"),
    EnableSsl = true,
    // UseDefaultCredentials = true

// Send the mail message

It will show up like this:

Who Unfriended me on Facebook?
The email that has been sent from the application
The email that has been sent from the application

Spread the word!

Leave a Reply

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