How To: Send Emails Using SMTP in C#

How To: Send Emails Using SMTP in C#

How to send mail using SMTP Server in C#

A colleague recently asked for help on how to send an email to his Gmail account. He's new to programming and was trying to send an email as practice. I directed him to different sites and articles I thought could help, however, He was not able to successfully run his application.

As a result, I decided to pick it up during my leisure.

While attempting to send a test email to my Gmail account, I ran into the same error He encountered, notwithstanding, being the Grand Developer that I am😎 I was able to resolve the issue.

For anyone looking for a summary of this article, I have provided the basic ideas below:

Issue I Encountered

image.png

How I Rectified It

  • I used a passcode generated within my Gmail account settings option.

For more details on how to go about the entire process, kindly continue reading.

Initial Requirements

Just like with your Gmail account and application, we will require a few details. We need:

  1. Sender Email Address - Email address sending the mail
  2. Receiver Email Address - Email address receiving the mail
  3. Sender Email Address Password -Password of the account sending the mail
  4. SMTP Server - Gmail's SMTP server address
  5. TLS Port - Gmail's TLS Port

Obviously, we require other information like the body of the email and the subject of the email, nonetheless, without the requirements stated above, we cannot send our email.

C# Requirements

In order to run our email application in C#, we will need two namespaces.

Namespace 1 - System.Net

A simple way of looking at System.Net is to see it as a logical group that contains the core classes designed for building applications that communicate over a network. Part of the core functions of these classes is the ability to upload to and download from resources on the Internet.

To send our email, we will be making use of the NetworkCredential Class. Specifically, the overloaded constructor NetworkCredential(String, SecureString)

This constructor initializes a new instance of the NetworkCredential class with the specified user name and password.

Refer to the code snippet below to see a use case.

Namespace 2: System.Net.Mail

Microsoft said it best - The System.Net.Mail holds classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery."

Within the class, we use MailMessage and SmtpClient. MailMessage represents an email message that can be sent using the SmtpClient class while SmtpClient allows applications to send an email using the Simple Mail Transfer Protocol (SMTP).

The Beautiful Code

Having said all that, it's time to see an implementation.

using System.Net;
using System.Net.Mail;
namespace SendMail
{
    class Program
    {
        static int gmailPortNumber = 587; //Gmail port number
        static string gmailSmtpAddress = "smtp.gmail.com";
        static string gmailPassword = "xxx"; //Sender Password 

        static string emailToAddress = "xxx@gmail.com"; //Receiver Email Address  
        static string emailFromAddress = "xxx@gmail.com"; //Sender Email Address  

        static string emailSubject = "Test Email";
        static string emailBody = "Just testing out sending email";

        static void Main(string[] args)
        {
            SendEmail(emailFromAddress, emailToAddress, gmailPassword, gmailPortNumber, gmailSmtpAddress, emailSubject, emailBody);
        }
        public static void SendEmail(string sender, string receiver, string password, int portNumber, string smtpAddress, string subject, string body)
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(sender);
                mail.To.Add(receiver);
                mail.Subject = subject;
                mail.Body = body;

                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(sender, password);
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                }
            }
        }

    }
}

As you may have noticed, I x'd out my details. Wouldn't want to receive any scary messages from anyone😏

Haha

Anyway, that is not what I want to point out. If you remember, the major reason I went through all this was to help a colleague send an email. And as I already mentioned, I still got the same error message after typing out this magnificent piece of code.

I got the error message:

image.png

Be that as it may, being the Grand Developer that I am😋 I was able to resolve it. Below is how I did it.

The Solution

Step 1:

Sign in to Gmail and Go to Settings

Step 2:

Go to Account and Import, and Click on other Google Account Settings

image.png

Step 3

Click on Security

image.png

Step 4

Click on App Passwords under Signing in to Google

image.png

Step 5

Select the App and Device you want to Generate a Password for

image.png

Step 6

Click on Generate

image.png

Step 7

Use the Code Generated as your Password within your Application

image.png

Step 8

Enjoy your Application!

Finally

In closing, I want to mention that there are a lot more ways other than the method I've discussed in this article to send an email. While I look forward to using them in a future article, I also encourage you to experiment with them. It'll help you as a developer and honestly, it's just fun trying new stuff out.

So until next time guys, keep going after the life you want without compromising on your values.

✌🏼