Subscribe to our YouTube Channel for more Videos

C# Tips and Tricks #10 – Send email via Gmail in C#


If wanna send email through gmail as the SMTP provider from your .NET application , here’s a sample code snippet that demonstrates how to do it.

 

How to send email through gmail in C#?

Use the System.Net.Mail namespace to send email via SMTP in C#. .NET provides the SmtpClient class which lets you to pass the necessary parameters to send an email via the specified SMTP settings.

using System;
using System.Net;
using System.Net.Mail;
namespace ConsoleApp1
{
    class Program
    {   
        static void Main(string[] args)
        {
            MailAddress from = new MailAddress("[email protected]", "<From Name>");
            MailAddress to = new MailAddress("<to email address>", "<To Name>");
            string subject = "Subject of the email";
            string body = "Body of the email";

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(from.Address, "<FromPassword>")
            };
            using (var message = new MailMessage(from, to)
            {
                Subject = subject,
                Body = body
            })
            
            smtp.Send(message);
            
            Console.ReadLine();
        }
    }
}
    
Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.