Sending emails in C#

C# provides an easy solutions for sending mails in just few steps.

Know it:

Prior to main code file we first must look onto the classes .NET provides for sending mails and working with smtp protocol. All the mentioned classes are present under System.Net.Mail namespace.

SmtpClient : Allows sending of emails using smtp protocol.
MailMessage : Represents the different parts of the email messages that we send via SmtpClient.

Implement it:

using System;
using System.Net.Mail;

namespace CodeForWin
{
    class Email
    {
        //Smpt server
        public const string GMAIL_SERVER = "smtp.gmail.com";
        //Connecting port
        public const int PORT = 587;

        static void Main(string[] args)
        {
            try
            {
                SmtpClient mailServer = new SmtpClient(GMAIL_SERVER, PORT);
                mailServer.EnableSsl = true;

                //Provide your email id with your password.
                //Enter the app-specfic password if two-step authentication is enabled.
                mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");

                //Senders email.
                string from = "[email protected]";
                //Receiver email
                string to = "[email protected]";

                MailMessage msg = new MailMessage(from, to);
                
                //Subject of the email.
                msg.Subject = "Enter the subject here";

                //Specify the body of the email here.
                msg.Body = "The message goes here.";

                mailServer.Send(msg);

                Console.WriteLine("MAIL SENT. Press any key to exit...");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to send email. Error : " + ex);
            }

            Console.ReadKey();
        }
    }
}

Here is a list of popular Smtp servers

Provider nameSmtp serverPort
Gmailsmtp.gmail.com587
Hotmailsmtp.live.com465
Outlooksmtp.live.com587
Office365smtp.office365.com587
Yahoo mailsmtp.mail.yahoo.com465
Yahoo mail plusplus.smtp.mail.yahoo.com465
Verizonoutgoing.yahoo.verizon.net587

Here is the next part of this post sending emails with attachment.

Happy coding 😉