How to Send Email in C#

In this step by step guide, we share how to send email in C# using Aspose.Email for .NET. We’re sending email using Gmail SMTP server in this C# console application, but you can send email using any SMTP server in any type of .NET applications.

Steps to Send Email in C#

  1. Setup Aspose.Email for .NET from NuGet package manager
  2. Include the following namespaces: Aspose.Email, Aspose.Email.Clients, and Aspose.Email.Clients.Smtp
  3. Apply license using Aspose.Email.License class
  4. Create a new email message using MailMessage class
  5. Create instance of SmtpClient class
  6. Set Gmail SMTP client information to send email through
  7. Send email using Send method of SmtpClient class

Code to Send Email Using C#

using System;
//Add Aspose.Email for .NET package reference
//Use following namespaces to convert OTG to PDF format
using Aspose.Email;
using Aspose.Email.Clients;
using Aspose.Email.Clients.Smtp;
namespace SendEmailUsingSMTPServer
{
class Program
{
static void Main(string[] args)
{
//Set Aspose license before sending email through Gmail SMTP
//using Aspose.Email for .NET
Aspose.Email.License AsposeEmailLicense = new Aspose.Email.License();
AsposeEmailLicense.SetLicense(@"c:\asposelicense\license.lic");
//create an instance of MailMessage
MailMessage EmailMessage = new MailMessage();
//Set email message properties which you want to specify
EmailMessage.Subject = "How to Send Mail Using SMTP Server in C#";
EmailMessage.To = "ReceiverEmail@EmailServer.com";
EmailMessage.Body = "This is a test of sending email using SMTP in C#.";
//Initiate an instance of SmptpClient class
SmtpClient SMTPEmailClient = new SmtpClient();
//Set SMTP client properties so the email message can get through the server
SMTPEmailClient.Host = "smtp.gmail.com";
SMTPEmailClient.Username = "YourEmail@gmail.com";
SMTPEmailClient.Password = "Your Gamil Password";
SMTPEmailClient.Port = 587;
SMTPEmailClient.SecurityOptions = SecurityOptions.SSLExplicit;
//Finally send the email message using Gmail's SMTP client
SMTPEmailClient.Send(EmailMessage);
}
}
}

Issue When you Send Email Using Gmail SMTP in C#

You might face an exception like “The SMTP server requires a secure connection or the client was not authenticated.”. This is because Gmail considers your application as less secure so may not allow to send email using their SMTP sever. To Fix Gmail SMTP issue allow access to less secure apps to send email.

 English