0

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. enter image description here

mnu-nasir
  • 1,642
  • 5
  • 30
  • 62
  • 1
    You need to set UseDefaultCredentials = false BEFORE Credentials. UseDefaultCredentials is complex (and stupid) property, it just clear out your Credentials field, so you basically send mail without credentials. Just switch them and everything should be alright. – eocron May 13 '21 at 17:55

1 Answers1

2

Switch those two lines:

smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false; //<----

to this:

smtp.UseDefaultCredentials = false; //<----
smtp.Credentials = new NetworkCredential(emailFromAddress, password);
smtp.EnableSsl = true;

It is veeeery good example how to NOT use properties. Setting one resets another. This should probably be a bug, but no one will fix this legacy.

PS this behavior is described in this post - The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

eocron
  • 6,885
  • 1
  • 21
  • 50