How to send emails in Dotnet

How to send emails in .NET and .NET Core with the standard System.Net.Mail namespace using Gmail

Monday, Aug 23, 2021

Introduction

.NET and .NET Core come with built-in support for sending emails through the System.Net.Mail namespace.

Prerequisites

  • Visual Studio installed on your system
  • A basic knowledge of .Net and C#

Send an Email

We will be using Google’s SMTP servers for this example, you will need to enable Less secure app access on your profile’s Security page: https://myaccount.google.com/lesssecureapps

var smtpClient = new SmtpClient("smtp.gmail.com")
{
  Port = 587,
  Credentials = new NetworkCredential("youremail@gmail.com", "yourpassword"),
  EnableSsl = true,
};

smtpClient.Send("youremail@gmail.com", "recipient@example.com", "Sending Email with .Net", "Hello World!");

There’s an overloaded Send-method that accepts a MailMessage object to help build the email message:

MailMessage message = new MailMessage("youremail@gmail.com", "recipient@example.com", "Sending Email with .Net", "Hello World!");
NetworkCredential netCred = new NetworkCredential("youremail@gmail.com","yourpassword");
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = netCred;
smtpClient.Send(message);

Using Mailazy

Mailazy supports both SMTP and Email API. With SMTP, you can use either the SmtpClient class or the MailKit package. All you need to do is to replace the SMTP server, port, and credentials with those obtained from Mailazy.

using System.Net;
using System.Net.Mail;

class Example
{
  static  void  Main(string[] args)
  {
    var mail = new MailMessage();

    //set the addresses
    mail.From = new MailAddress("sender@example.com", "sender");
    mail.To.Add("recipient@example.com");

    //set the content
    mail.Subject = "Sending with Mailazy";

    //set the plain text part
    var plainView = AlternateView.CreateAlternateViewFromString("Hello World!", System.Text.Encoding.UTF8,
    "text/plain");
    //then set the html part
    var htmlView = AlternateView.CreateAlternateViewFromString("<b>Hello World!</b>",
    System.Text.Encoding.UTF8, "text/html");
    mail.AlternateViews.Add(plainView);
    mail.AlternateViews.Add(htmlView);

    //send the message
    var smtp = new SmtpClient("smtp.mailazy.com", 587);
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("<access_key>", "<access_secret>");
    smtp.EnableSsl = true;
    smtp.Send(mail);
  }
}