How to send an e-mail via Google SMTP using C#

First things first, some useful StackOverflow links:

https://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp

https://stackoverflow.com/questions/17462628/the-server-response-was-5-7-0-must-issue-a-starttls-command-first-i16sm1806350

To demonstrate how this is done I first create a new Visual Studio project:

Some example code for sending an email via a Google email account (smtp.goolgle.com) – obviously replace this with email / credentials of your own…

I put the code within a try-catch block in order to capture any errors that may occur while attempting this.

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

namespace EmailSmtp
{
   class Program
   {
      static void Main(string[] args)
      {
         try
         {
            // Credentials
            var credentials = new NetworkCredential("someEmail@gmail.com", "somePassword");

            // Mail message
            var mail = new MailMessage()
            {
               From = new MailAddress("someEmail@gmail.com"),
               Subject = "Test email.",
               Body = "Test email body"
            };

            mail.To.Add(new MailAddress("someEmail@gmail.com"));

            // Smtp client
            var client = new SmtpClient()
            {
               Port = 587,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Host = "smtp.gmail.com",
               EnableSsl = true,
               Credentials = credentials
            };

            // Send it...         
            client.Send(mail);
         }
         catch (Exception ex)
         {
            Console.WriteLine("Error in sending email: " + ex.Message);
            Console.ReadKey();
            return;
         }

         Console.WriteLine("Email sccessfully sent");
         Console.ReadKey();
      }
   }
}

On attempting to run the program, you might get an error similar to “Error in sending email: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.”

If this is the case then navigate to your Google account and allow it to run less secure app (set to ON) – this is what I did for the purposes of demonstration, and you can always turn this back to OFF, given that there may be risks to doing this.

https://www.google.com/settings/security/lesssecureapps

So that on attempting to send the email again, your Google account allows it:

And on inspecting my Google email account see that I receive the warning from Google that access to less secure apps has been turned ON, plus the email I sent to myself to test the program: