我在代码中遇到异常,例如未经身份验证

本文关键字:身份验证 异常 代码 遇到 | 更新日期: 2023-09-27 18:32:59

SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("xxxxxx@gmail.com", "xxxxxxxx", "smtp.gmail.com");
smtpClient.UseDefaultCredentials = false;
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(TextBox2.Text.Trim());
mailMessage.From = new MailAddress("xxxxxx@gmail.com");
mailMessage.IsBodyHtml = true;
mailMessage.Subject = "Thanks for registering to Doctor Search";
mailMessage.Body = "<a href='http://localhost:1668/templatemo_418_form_pack/OTP.aspx?ctk=" + ss + "'>Click here to verify your Mobile</a>";
smtpClient.Send(mailMessage);

我收到一个错误:

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

我不明白这背后的原因是什么

我在代码中遇到异常,例如未经身份验证

我正在使用这个:

public void SendEmailWithGmail(string emailContent, string emailRecipients, string emailSubject)
    {
        var @from = _emailSendFrom;  //Replace this with your own correct Gmail Address
        var _to = emailRecipients;

        var mail = new System.Net.Mail.MailMessage();
        mail.To.Add(_to);
        mail.From = new System.Net.Mail.MailAddress(@from, _emailDisplayName, System.Text.Encoding.UTF8);           
        mail.Subject = emailSubject;
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Body = emailContent;
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = true;
        mail.Priority = System.Net.Mail.MailPriority.High;

        var client = new SmtpClient
        {
            Credentials = new System.Net.NetworkCredential(@from, GmailPsw),
            Port = 587,
            Host = "smtp.gmail.com",
            EnableSsl = true
        };

            client.Send(mail);
    }