在 .NET Core 应用程序中使用 gmail smtp 服务发送电子邮件失败

Email sending fail using gmail smpt service in .NET Core application

我已经创建了一个 .net core 3.1 控制台应用程序。我想使用 gmail smtp 服务发送电子邮件。这是我的代码:

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);
                }
            }
        }
    }

但我发现以下异常:

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.

在我的 gmail 设置中,我已经打开了不太安全的应用程序访问选项。

切换这两行:

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

对此:

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

如何不使用属性是一个很好的例子。设置一个重置另一个。这应该是一个错误,但没有人会修复这个遗留问题。

PS 此行为在 post - The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

中有所描述