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

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("yoursender@gmail.com");

// Recepient address
mMailMessage.To.Add(new MailAddress("yourrecepient@gmail.com"));

// Bcc address
mMailMessage.Bcc.Add(new MailAddress("bccaddress123@gmail.com"));

// CC address
mMailMessage.CC.Add(new MailAddress("ccaddress123@gmail.com"));

// 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.
mMailMessage.Attachments.Add(data);

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

// Priority
mMailMessage.Priority = MailPriority.Normal;

// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient("smtp.gmail.com", 587)
{
    Credentials = new NetworkCredential("yoursender@gmail.com", "yourpassword"),
    EnableSsl = true,
    // UseDefaultCredentials = true
};

// Send the mail message
mSmtpClient.Send(mMailMessage);

It will show up like this:

The email that has been sent from the application
The email that has been sent from the application

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment