简体   繁体   English

当发送帐户使用两因素身份验证时,如何通过Gmail和SmtpClient发送电子邮件?

[英]How do I send an email with Gmail and SmtpClient when the sending account uses two factor authentication?

            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential =
                new NetworkCredential("sender@gmail.com", "password");
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress("sender@gmail.com");

            smtpClient.EnableSsl = true;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;

            message.From = fromAddress;
            message.Subject = "your subject";
            //Set IsBodyHtml to true means you can send HTML email.
            message.IsBodyHtml = true;
            message.Body = "<h1>Hello, this is a demo ... ..</h1>";
            message.To.Add("receiver@gmail.com");

            try
            {
                smtpClient.Send(message);
            }
            catch (Exception ex)
            {
                //Error, could not send the message
                ex.ToString();
            }

// The thing is that this code works fine for gmails without phone number protection. //问题是,此代码适用于没有电话号码保护功能的gmail。 Exception occurs when using this code with gmails that are protected(verified) via the client phone number. 将此代码与通过客户电话号码受保护(验证)的Gmail一起使用时,会发生异常。

One of the solution is to use a remote server to access clients mails. 解决方案之一是使用远程服务器访问客户端邮件。

Now my question is there another method to solve this issue ? 现在我的问题是还有另一种方法可以解决此问题吗? other than third parties. 除了第三方。

If I understand you correctly, you're saying the Google account is using two-factor authentication. 如果我正确理解您的意思,是说Google帐户正在使用两因素身份验证。

If that's the case, you need to create an Application Password for this. 在这种情况下,您需要为此创建一个应用程序密码。 Go to https://security.google.com/settings/security/apppasswords once logged in as the account you want to two-factor auth with. 以您要进行双重身份验证的帐户身份登录后, 转到https://security.google.com/settings/security/apppasswords

In the list, under Select App choose "Other" and give it some name. 在列表中的“ Select App ”下, Select App “其他”并为其命名。 Click Generate, and write this password DOWN cause you will only ever see it ONCE. 单击“生成”,然后将此密码记为“ DOWN”,因为您只会一次看到该密码。 You will use this in your authentication. 您将在身份验证中使用它。 It will be 16-characters long and the spaces don't matter, you can include them or omit them. 长度为16个字符,空格无关紧要,您可以包含或忽略它们。 I included them here just because. 我之所以将它们包括在这里是因为。

NetworkCredential basicCredential =
            new NetworkCredential("sender@gmail.com", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM