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

﹥>﹥吖頭↗ 提交于 2020-07-23 03:28:06

问题


            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. Exception occurs when using this code with gmails that are protected(verified) via the client phone number.

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.


回答1:


If I understand you correctly, you're saying the Google account is using two-factor authentication.

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.

In the list, under Select App choose "Other" and give it some name. Click Generate, and write this password DOWN cause you will only ever see it ONCE. 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. I included them here just because.

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


来源:https://stackoverflow.com/questions/28549936/how-do-i-send-an-email-with-gmail-and-smtpclient-when-the-sending-account-uses-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!