C# Tips and Tricks #10 – Send email via Gmail in C#

If wanna send email through gmail as the SMTP provider from your .NET application , here’s a sample code snippet that demonstrates how to do it.

 

How to send email through gmail in C#?

Use the System.Net.Mail namespace to send email via SMTP in C#. .NET provides the SmtpClient class which lets you to pass the necessary parameters to send an email via the specified SMTP settings.

using System;
using System.Net;
using System.Net.Mail;
namespace ConsoleApp1
{
    class Program
    {   
        static void Main(string[] args)
        {
            MailAddress from = new MailAddress("[email protected]", "<From Name>");
            MailAddress to = new MailAddress("<to email address>", "<To Name>");
            string subject = "Subject of the email";
            string body = "Body of the email";

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(from.Address, "<FromPassword>")
            };
            using (var message = new MailMessage(from, to)
            {
                Subject = subject,
                Body = body
            })
            
            smtp.Send(message);
            
            Console.ReadLine();
        }
    }
}
    

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...