Mahmoud Ghandour
Mahmoud Ghandour

Reputation: 63

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("[email protected]", "password");
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress("[email protected]");

            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("[email protected]");

            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.

Upvotes: 5

Views: 5994

Answers (1)

Mark S
Mark S

Reputation: 401

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("[email protected]", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

Upvotes: 13

Related Questions