使用 smtp 客户端发送电子邮件时如何修复 smtp 身份验证运行时错误?

How to fix the smtp authentication runtime error when sending email using smtp client?

我在我的应用程序中使用 smtp 客户端发送简单的电子邮件消息,我之前使用过这段代码,它工作正常。现在,当我尝试从我的本地主机再次 运行 我的项目并尝试发送电子邮件时。我收到一个 运行 时间错误,显示

SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 需要身份验证。

我不知道刚刚发生了什么,因为它之前工作正常。现在我无法发送电子邮件,我得到的只是这个错误。我几乎无法解决问题所在。我该如何解决这个问题?下面是我的代码:谢谢...

SmtpClient client = new SmtpClient();

                client.Host = "smtp.gmail.com"; 

                client.Port = 587;

                client.EnableSsl = true;

                client.Credentials = new System.Net.NetworkCredential(@"myemailaddress@gmail.com",@"myemailpassword");            

                // create message
                MailMessage message = new MailMessage();

                message.From = new MailAddress(TextBox4.Text);
                message.To.Add(new MailAddress(TextBox1.Text));
                message.Subject = TextBox2.Text;
                message.Body = TextBox3.Text; //body of the message to be sent
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                // message.Subject = "subject";
                message.SubjectEncoding = System.Text.Encoding.UTF8;

               try
               {
                    client.Send(message);
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Mail has been successfully sent!')", true);

                }
                catch (SmtpException ex)
                {

                    Response.Write(ex.Message);

                }
                finally
                {
                    // Clean up.
                    message.Dispose();
                }

只需转到此处:Less secure apps,使用用于在 C# 代码中发送邮件的电子邮件和密码登录,然后选择 Turn On

另请转到此 link 并单击 继续 Allow access to your Google account

我也稍微编辑了一下:

public string sendit(string ReciverMail)
{
    MailMessage msg = new MailMessage();

    msg.From = new MailAddress("YourMail@gmail.com");
    msg.To.Add(ReciverMail);
    msg.Subject = "Hello world! " + DateTime.Now.ToString();
    msg.Body = "hi to you ... :)";
    SmtpClient client = new SmtpClient();
    client.UseDefaultCredentials = true;
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");
    client.Timeout = 20000;
    try
    {
       client.Send(msg);
        return "Mail has been successfully sent!";
    }
    catch (Exception ex)
    {
        return "Fail Has error" + ex.Message;
    }
    finally
    {
       msg.Dispose();
    }
}