Google+ How to Send Mail With Gmail And C#

Peter Bromberg's .NET Blog All Things Programming

How to Send Mail With Gmail And C#

3. June 2021 14:27 by admin in

Many developers have difficulty sending mail through Gmail because of security issues. Google provides what is called an "app-specific password" that can be used if you have 2-factor authentication turned on (you should!).

Here is the URL to set this up:  And here is some sample C# code to use it. You simply replace your regular gmai password with the app-specific password that you set up in your Google settings.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace SendMail
class Program
static string smtpAddress = "";
static int portNumber = 587;
static bool enableSSL = true;

static string emailFromAddress = ""; //Sender Email Address
static string password = "APPSPECIFICPWD"; //APP SPECIFIC PWD Generated at Google Account
static string emailToAddress = ""; //Receiver Email Address
static string subject = "Hello";
static string body = "Hello, This is Email sending test using gmail.";

static void Main(string[] args)


public static void SendEmail()
using (MailMessage mail = new MailMessage())
mail.From = new MailAddress(emailFromAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// mail.Attachments.Add(new Attachment("C:\\Temp\\TestFile.txt"));//--Uncomment this to send any attachment

using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = enableSSL;


Add comment

  Country flag