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("myemail@gmail.com", "mypassword");

                //Senders email.
                string from = "codeforwin@gmail.com";
                //Receiver email
                string to = "reciever@gmail.com";

                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 name Smtp server Port
Gmail smtp.gmail.com 587
Hotmail smtp.live.com 465
Outlook smtp.live.com 587
Office365 smtp.office365.com 587
Yahoo mail smtp.mail.yahoo.com 465
Yahoo mail plus plus.smtp.mail.yahoo.com 465
Verizon outgoing.yahoo.verizon.net 587

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

Happy coding ;)

Labels: , , , ,