Send an email using Gmail SMTP in C#

Introduction


In this tutorial, i will show you how to send an email using Gmail SMTP (Simple Mail Transfer Protocol) in C#.

SMTP Configuration


In your Web.config or App.config file, add the below code inside <configuration></configuration> tags.

<system.net>
    <mailSettings>
        <smtp from="abdrahmanbayan@gmail.com">
            <network host="smtp.gmail.com" port="587" userName="abdrahmanbayan@gmail.com" password="*****" enableSsl="true" />
        </smtp>
    </mailSettings>
</system.net>
host (the server that will deliver the email) smtp.gmail.com
port 587
userName your email address
password your password
enableSsl true

SMTP in C#


The following code illustrates how to send an email via SMTP.

MailMessage mailMessage = new MailMessage {
    Subject = "Testing SMTP", // Email subject
    Body = "Hello World !", // Email content
};

// destination
mailMessage.To.Add("abdrahmanbayan@gmail.com");

using (SmtpClient smtp = new SmtpClient()) {
    smtp.Send(mailMessage);
}

In preceding code, we create a new instance of the MailMessage class which represents the email we want to send via SMTP. We set the destination of the email (same address in this example) by adding it to the recipients collection using the Add method. After that, we instantiate the SmtpClient class and then we call the Send method to send our email (passed as a parameter of the method) to its recipient.


And this is the result:

Result of sending email via SMTP in C#

Namespace


To use SMTP objects in your code, you have to include this namespace:

using System.Net.Mail;

Note: if you get this error message:

System.Net.Mail.SmtpException

Turn on access for less secure apps

Turning access on for less secure apps