Solved: Failed to send email through Gmail - The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required Options

codeling 1196 - 5094
@2019-12-23 20:47:58

I am using the following C# code to send email via Gmail:

static public void SendMail(Pages.ForumPage basePage, System.Net.Mail.MailAddress fromAddress, System.Net.Mail.MailAddress toAddress, string subject, string body)
        {
            int port = 587;
            string smtpServer = "smtp.gmail.com";
            string smtpUserName = "myGmailAccount";
            string smtpUserPass = "myGmailPassword";

            using (SmtpClient smtpSend = new SmtpClient())
            {
                smtpSend.Host = smtpServer;
                smtpSend.Port = port;

                smtpSend.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpUserPass);

                smtpSend.EnableSsl = true;

                MailMessage emailMessage = new System.Net.Mail.MailMessage();

                emailMessage.To.Add(toAddress);
                emailMessage.From = fromAddress;
                emailMessage.Subject = subject;
                emailMessage.Body = body;

                if (!Regex.IsMatch(emailMessage.Body, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase) ||
                        !Regex.IsMatch(emailMessage.Subject, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase))
                {
                    emailMessage.BodyEncoding = Encoding.Unicode;
                }

                smtpSend.Send(emailMessage);
            }
        }

When I run this code, I get the following error message:

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. Learn more at
   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

 

 

codeling 1196 - 5094
@2019-12-23 21:06:25

With a lot of googling and fail-and-try loop, I finally resolved this issue. Here is the anwser to the above question:

1.Turn on "Less secure app access" in your Gamil email account:

2.Sign in Gmail using your Gmail account from the machine where you are runing the program.

You will be alerted from Google saying that you are signing in from a new device, Google needs you prove you are the guy who is signing in by inputting the verfication code via text mesage, phone call or email.

This step is very important, I am stuck here for a lot of time.

3.Run your program again.

Users browsing this topic
Guest