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 = "";
//Connecting port
public const int PORT = 587;

static void Main(string[] args)
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("", "mypassword");

//Senders email.
string from = "";
//Receiver email
string to = "";

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.";


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


Here is a list of popular Smtp servers

Provider name Smtp server Port
Gmail 587
Hotmail 465
Outlook 587
Office365 587
Yahoo mail 465
Yahoo mail plus 465
Verizon 587

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

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>