C#: Send an email using Google’s SMTP server.

I want to demonstrate how to write a simple console application that will use Google’s SMTP server to send an email. SMTP stands for Simple Mail Transfer Protocol which is the standard for delivering electronic mails over the Internet.

Before continuing you will need to have an email account with Google first, and if you dont please do it first. (Signup for GMail Account)

Startup Visual Studio and File->New->Project and select Visual C# Console Application Template, enter GoogleSmtpApp as the project name and continue.

In our code I am going to use the System.Net.Mail.SmtpClient class to send an email to a recipient. So in your Main method in your program.cs file create a new instant of the SmtpClient() class, to use this class you also need to enter smtp.gmail.com and port 587 in the class constructor.

var smtpClient = new SmtpClient("smtp.gmail.com", 587);

Before we can send an email there is four properties that needs to be set. UseDefaultCredentials must be set to false this will prevent default credentials sent as part of the request. DeliveryMethod must be set to Network so that the message will be sent through the network to the smtp server. Credentials must contain your Gmail username and password so that it can authenticate when connecting to the smtp server. EableSsl must be set to true so that our connection can be encrypted.

var smptClient = new SmtpClient("smtp.gmail.com", 587)
{
     UseDefaultCredentials = false,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     Credentials = new NetworkCredential("username@gmail.com", "password"),
     EnableSsl = true
};

Finally from the SmtpClient class we can call the method Send(). The Send method has two overloaded method but I will be using the one where I will provided the from, recipient, subject and body as strings. Make sure you replace the appropriate parameters with your own values.

smptClient.Send("from@email.com", "recipient@email.com", "subject", "body");

If you press F5 now to run your console application and wait and check your inbox to see if you have received an email! Anyways I hope this simple demonstration can show you how easily we can use Google’s smtp server to send a basic text email.

You can get the latest source code for this project from my GitHub account here:

GitHub: Google-Smtp-App

Shares