首页 > 解决方案 > SMTP 服务器需要安全连接或客户端未通过身份验证。请帮帮我

问题描述

我想从我的应用程序中发送一封电子邮件,以验证我用来注册但收到此错误的电子邮件。

The SMTP server requires a secure connection or the client was not authenticated. The server response 
was: 5.7.57 SMTP; 

我尝试进入我的 Gmail 设置并允许不太安全的应用程序打开,但它仍然无法正常工作。

用户控制器.cs

[NonAction]
    public void SendVerificaitonLinkEmail(string email, string activationCode, string emailFor = "VerifyAccount")
    {
        var verifyUrl = "/User/" + emailFor + "/" + activationCode;
        var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

        var fromEmail = new MailAddress("dotnetawesome@gmail.com", "Dotnet Awesome");
        var toEmail = new MailAddress(email);
        var fromEmailPassword = "**********"; // Replace with actual password

        string subject = "";
        string body = "";
        if (emailFor == "VerifyAccount")
        {
            subject = "Your account is successfully created!";

            body = "<br/><br/>We are excited to tell you that your Rockstar Awesome account is" +
                " successfully created. Please click on the below link to verify your account" +
                " <br/><br/><a href ='" + link + "'>" + link + "</a> ";
        }
        else if (emailFor == "ResetPassword")
        {
            subject = "Reset Password";
            body = "Hi, <br/><br/> We got request for reset your account password. Please click on the link below to reset your password." +
                "<br/><br/><a href = " + link + ">Reset Password link </a>";
        }



        SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        {
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword);
        };

        using (var message = new MailMessage(fromEmail, toEmail)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        })
            client.Send(message); // 
    }

标签: c#

解决方案


我推荐使用MailKithttps://github.com/jstedfast/MailKit)——代码维护得更好,更容易使用,而且作者实际上回应了 github 上的问题。内置的 .netSmtpClient不再维护。

并不是说这会解决您的问题,但值得一试 - 您可以连接一个 smtp 客户端,然后调用身份验证并最终开始发送消息,从而更容易识别故障点。

示例MailKit

var message = new MimeKit.MimeMessage();
message.From.Add(new MimeKit.MailboxAddress("Name From", "YOU_FROM_ADDRESS@gmail.com"));
message.To.Add(new MimeKit.MailboxAddress("Name To", "YOU_TO_ADDRESS@gmail.com"));
message.Subject = "Subject Line";

message.Body = new MimeKit.TextPart("plain")
{
    Text = @"Mail body message"
};

using var client = new MailKit.Net.Smtp.SmtpClient();
client.Connect("smtp.gmail.com", 587);
client.Authenticate("YOUR_GMAIL_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);

推荐阅读