delphigmailindy

Sending email via GMail with app specific password


I maintain and develop a program that (amongst other things) sends emails via GMail.

Until now, there have been no problems with sending emails, but a few days ago this functionality ceased to work with a message 'Bad credentials'. I looked through the help of GMail and found this explanation/warning/what-have-you:

To help keep your account secure, from May 30, 2022, ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

The solution is to use the 'app specific' password.

I looked at this question that states:

My most recent try was to create an 'app specific' password on Gmail

But the attached code doesn't actually show how the password is sent.

Reading the question and its answers, I made some changes to my program:

Port := 995
UseTLS := utUseImplicitTLS
SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2]

After these changes, in an attempt to send a test mail (still no app specific password), I get the response

Reply code is not valid: +OK

which might mean that my program fails, as it doesn't send the app specific password.

What I want to know is: how to send that password?

Below is my code that executes as a thread, hence all components are defined in code:

 email:= TIdMessage.Create (nil);
 try
  email.LoadFromFile (FFileName);
  email.OnInitializeISO:= DoInitializeISO;
  //  DeleteFile (FFileName);

  smtp:= TIdSMTP.Create (nil);
  try
   smtp.OnFailedRecipient:= FailedRecipient;
   ssl:= TIdSSLIOHandlerSocketOpenSSL.Create (smtp);
   ssl.SSLOptions.SSLVersions:= [sslvTLSv1];

   smtp.OnStatus := DoStatus;
   smtp.IOHandler:= ssl;
   smtp.Host:= FHost;
   smtp.Password:= FPassword;   // now app passord
   smtp.Username:= FUsername;
   smtp.UseTLS:= utUseExplicitTLS;
   smtp.Port:= 587;

   smtp.Connect;
   try
    smtp.Send (email);
   finally
    smtp.Disconnect;
   end;
  finally
   ssl.free;
   smtp.Free;
  end;
 finally
  email.Free;
 end;

Solution

  • An application-specific password is simply a password that Gmail generates for you, and then you use it instead of your normal password (ie, in the TIdSMTP.Password property). This is explained in Gmail's documentation:

    Sign in with App Passwords