Sending Emails in .NET Core 2.0 with Gmail

If you want to send email from a .NET Core 2.0 application and don't have access to your own SMTP server you may want to try using a Gmail account instead. It provides all the features you'd expect, you just to register a free Gmail account first.

Once you've set up an account you can use the sample below to send emails from ASP.NET Core and .NET Core Console applications.

First you'll need to import the following namespaces:

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

Then use the following code:

using (var message = new MailMessage())
{
    message.To.Add(new MailAddress("[email protected]", "To Name"));
    message.From = new MailAddress("[email protected]", "From Name");
    message.CC.Add(new MailAddress("[email protected]", "CC Name"));
    message.Bcc.Add(new MailAddress("[email protected]", "BCC Name"));
    message.Subject = "Subject";
    message.Body = "Body";
    message.IsBodyHtml = true;

    using (var client = new SmtpClient("smtp.gmail.com"))
    {
        client.Port = 587;
        client.Credentials = new NetworkCredential("[email protected]", "password");
        client.EnableSsl = true;
        client.Send(message);
    }
}

Don't forget to replace the [email protected] with your Gmail address. Try not to hard-code the password here as I've done, it's not very secure and could also get checked into source control by accident. Always follow best practice on the storage of passwords in applications, perhaps by storing an encrypted value in the appsettings.json and decrypting at runtime or using a secure password storage application.

Code Breakdown

using (var message = new MailMessage())

We're using the using statement here because the MailMessage object implements IDisposable. This tells us that it deals with unmanaged resources and needs to be disposed of after use, otherwise it'll hang around and could cause a memory leak.

message.To.Add(new MailAddress("[email protected]", "To Name"));
message.CC.Add(new MailAddress("[email protected]", "CC Name"));
message.Bcc.Add(new MailAddress("[email protected]", "BCC Name"));

You can add any number of email addresses in the To, CC and BCC fields in the email along with the name of each recipient so the emails look a bit more professional.

message.From = new MailAddress("[email protected]", "From Name");

The From address is important. This will be the email address that the email looks like it came from and will also be the address that the reply will go to when the reply button is hit in the email client.

message.Subject = "Subject";
message.Body = "Body";

Here we're just setting the string values of the subject and body. The content of the message.Body field can be HTML if you set the message.IsBodyHtml flag to true (although the default is true, you don't really need to set it unless you want to be completely sure.

If you set the message.IsBodyHtml flag to false then the email will be sent as plaintext and look pretty boring.

SMTP Server

using (var client = new SmtpClient("smtp.gmail.com"))

Here we're newing up an SmtpClient pointing at the host smtp.gmail.com. This is the hostname of Gmail's SMTP server and the place where our email will be injected for delivery. If the email address we're sending to resides on Gmail's own servers it won't have very far to go but if the address is a non-Gmail address then this server will forward it on so that it eventually finds the recipient's SMTP server and is able to deliver it to their inbox.

client.Port = 587
client.EnableSsl = true

Port 587 is an industry standard port for secure email communications which means the communication will happen over a secure connection known as TLS. This is to ensure that if anyone is listening between your application and Gmail's SMTP servers that they'll just get a load of encrypted junk rather than being able to see your username, password and information about the email you're sending.

client.Credentials = new NetworkCredential("[email protected]", "password");

SMTP servers tend to require authentication because many have been wildly abused in the past. An incorrectly configured SMTP server can potentially allow anyone to send emails (this is generally known as an 'open relay' and are responsible for a lot of spam and illegal mail). Most SMTP servers nowadays will require authentication before they'll accept mail from you.

And last but not least:

client.Send(message);

This tells your client to begin the process of passing the email data onto the SMTP server. It will require connecting to a 3rd party remote server so following best practice it's always a good idea to put a try { } catch { } around this part as you could get an exception and it'll be nice to handle it gracefully.

If you're building an application that sends emails on behalf of users it's always a good idea to handle a send failure and let the user know of alternative ways to contact you, such as by email or phone.

Troubleshooting

With Gmail you may get an exception that looks like the following:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

If this happens it's worth logging into the Gmail account that you're sending with and enabling less secure apps.

If you've still got issues afterwards it might be worth following some other suggestions in this Stack Overflow post on Gmail exceptions.

Happy sending!