GMail SMTP

Question:

I am trying to send email via GMail using the SMTP protocol.  I am sending the correct GMail login credentials, but I get this error:

...
smtpAuthenticate:
login_method: LOGIN
auth_login:
  smtpSendGet2:
    sendCmdToSmtp:
      SmtpCmdSent: AUTH LOGIN
    --sendCmdToSmtp
    readSmtpResponse:
      SmtpCmdResp: 334 VXNlcm5hbWU6
    --readSmtpResponse
  --smtpSendGet2
  sendCmdToSmtp:
    SmtpCmdSent: ***
  --sendCmdToSmtp
  readSmtpResponse:
    SmtpCmdResp: 334 UGFzc3dvcmQ6
  --readSmtpResponse
  sendCmdToSmtp:
    SmtpCmdSent: {PasswordOrCredentials}
  --sendCmdToSmtp
  readSmtpResponse:
    SmtpCmdResp: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsG
    SmtpCmdResp: 534-5.7.14 n5rYM4PYxPR7YqQVlbTxdmbVimcii93TX6k3aJfKcd8hxX2ZWmUoO-2Giu8N_A5HA827H6
    SmtpCmdResp: 534-5.7.14 …
    SmtpCmdResp: 534-5.7.14 …
    SmtpCmdResp: 534-5.7.14 srCFutiZ4TpRrybTHxXsHbPI9ZJwwT1jcgBndgFUxr-wzlktVW> Please log in via
    SmtpCmdResp: 534-5.7.14 your web browser and then try again.
    SmtpCmdResp: 534-5.7.14  Learn more at
    SmtpCmdResp: 534 5.7.14  https://support.google.com/mail/answer/78754 v76sm3334299pfj.145 - gsmtp
  --readSmtpResponse
...

Answer:

SMTP LOGIN authentication (using a login and password over TLS) is considered by Google to be “less secure”.  Therefore, the GMail account needs to be configured for “less secure apps”.  The GMail account owner can do it here:  https://myaccount.google.com/lesssecureapps

There are two alternatives that don’t require the GMail account to be configured for “less secure apps”.

  1. Use OAuth2 authentication.  This requires an initial step that displays a web browser allowing the GMail account owner to authorize the application for sending email.  The result of this authorization is an access token that is used for SMTP OAuth2 authentication (rather than using a login/password).  The access token will need to be periodically refreshed, but the refresh can be done without GMail account owner interaction.  (In other words, displaying the web browser is a 1-time action.  The access token obtained from the authorization is persisted to a database, file, etc. so that it is re-used and refreshed as needed for all future SMTP sessions.)
    See: Get GMail SMTP OAuth2 Access Token for Desktop App
    GMail SMTP Send using Previously Obtained OAuth2 Access Token
    Refresh GMail SMTP OAuth2 Access Token
    OAuth2 for a GMail using a Service Account Key
  2. Use GMail Rest API.  It is also possible to send email using the GMail REST API.  This is sending email via HTTPS as opposed to using the SMTP protocol.
    See examples here:  https://www.example-code.com/csharp/gmail.asp
    (The same GMail REST API examples are available for many other programming languages under the “GMail REST API” category on example-code.com.)