How to Send email in .NET through Gmail

It is easy to send email in .net through Gmail using the System.Net.Mail namespace. The below example will help you to send a simple plain mail using Gmail SMTP method. MailMessage Class has a lot of properties which can be used if you need to build a mail application.

C# Code to send email in .net through Gmail

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

var fromAddress = new MailAddress("", "From Name");
var toAddress = new MailAddress("", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
    Host = "",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
using (var message = new MailMessage(fromAddress, toAddress)
    Subject = subject,
    Body = body

Let us take another example to send email in .net through Gmail using file attachment.

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

public void email_send()
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("");
    mail.From = new MailAddress("");
    mail.Subject = "Your Subject";
    mail.Body = "Body Content goes here";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/file.txt");

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("", "mailpassword");
    SmtpServer.EnableSsl = true;


Few of the MailMessage Properties which you should be knowing while using the above method.

  • Mail Attachments: If you would like to send any attachments in the mail then you could use System.Net.Mail.Attachment attachment =new System.Net.Mail.Attachment(“c:/file.txt”);  and then add the attachment to your MailMessage object using mail.Attachments.Add(attachment);
  • HTML Body: If you would like to send the HTML content message in the mail then you should set the MailMessage HTML property as mail.IsBodyHtml = true;
  • CC and BCC Address: If you would like to add the CC and BCC mail address then you should use the below properties to achieve this functionality.
  • Delivery Notifications: If you would like to get the delivery notification on success or failure then you can set the delivery notification type while sending the message.
    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like