Skip to content

Sending email with GMail’s SMTP server in ASP.NET

Sending email via SMTP in ASP.NET is a really painless experience.  However, there are a couple of hoops to jump through if you want to use Google’s GMail SMTP servers.  The following example shows a really simple function to get the job done.

The Google support page for configuring a mail client gives us a good starting point.  We can see that we need to use the host smtp.gmail.com on port 587.  We can also see that we must transmit over a secure connection and that we need to use our GMail username and password to authenticate with the server.

using System.Net.Mail;

public class GMailSMTP
{
    public void Send(string to, string subject, string message, bool isHtml)
    {
            // Create a new message
            var mail = new MailMessage();

            // Set the to and from addresses.
            // The from address must be your GMail account
            mail.From = new MailAddress("example@gmail.com");
            mail.To.Add(new MailAddress(to));

            // Define the message
            mail.Subject = subject;
            mail.IsBodyHtml = isHtml;
            mail.Body = message;

            // Create a new Smpt Client using Google's servers
            var mailclient = new SmtpClient();
            mailclient.Host = "smtp.gmail.com";
            mailclient.Port = 587;

            // This is the critical part, you must enable SSL
            mailclient.EnableSsl = true;

            // Specify your authentication details
            mailclient.Credentials = new System.Net.NetworkCredential(
                                             "YOUR GMAIL USERNAME",
                                             "YOUR GMAIL PASSWORD");
            mailclient.Send(mail);
    }
}
That's all there is to it!