I have created a .net core 3.1 console application. I want to send email using gmail smtp service. here is my code:
class Program
{
static string smtpAddress = "smtp.gmail.com";
static int portNumber = 587;
static string emailFromAddress = "from_email@gmail.com";
static string password = "###########";
static string emailToAddress = "to_email@gmail.com";
static string subject = "Hello";
static string body = "Hello, This is Email sending test using gmail.";
static void Main(string[] args)
{
SendEmail();
Console.WriteLine("Hello World!");
}
public static void SendEmail()
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFromAddress);
mail.To.Add(emailToAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
}
}
}
}
But I find the below exception:
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
In my gmail settings I have already turned on the Less Secure App access option.