Delphi - Send email using Gmail/G Suite OAuth 2.0 in background service (service account)

By default, you need to enable ” Allowing less secure apps” in Gmail/G Suite/Google Workspace, then you can send email with user/password SMTP authentication.

However Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.

Installation

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). Before you can use the following example codes, you should download the EASendMail Installer and install it on your machine at first.

Add reference

To use EASendMail SMTP ActiveX Object in your Delphi project, the first step is “Add Unit file of EASendMail to your project”. Please go to C:\Program Files\EASendMail\Include\delphi or C:\Program Files (x86)\EASendMail\Include\delphi folder, find EASendMailObjLib_TLB.pas, and then copy this file to your project folder.

unit Unit1;

interface
// include EASendMailObjLib_TLB unit to your Delphi Project
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, EASendMailObjLib_TLB, StdCtrls;

You can also create “EASendMailObjLib_TLB.pas” manually like this:

  • Delphi 7

    Please choose menu -> Project -> Import Type Library and select EASendMailObj ActiveX Object, click Create Unit, the reference of EASendMail ActiveX Object will be added to your project.

    add reference in Delphi
  • Delphi XE

    If you use Delphi XE to import the Type library, Please choose menu -> Component -> Import Component -> Import Type Library -> and select EASendMailObj ActiveX Object -> have Generate Component Wrapper checked -> Create Unit.

Then you can start to use it in your Delphi Project.

Google Service Account

Normal OAuth requires user input user/password in Web Browser. Obviously, it is not suitable for background service. In this case, you should use google service account to access G Suite or Google Workspace email service without user interaction. Service account only works for G Suite or Google Workspace user, it doesn’t work for personal Gmail account.

Create project in Google Developers Console

To use “G Suite or Google Workspace Service Account OAuth” in your application, you should create a project in Google Cloud Console at first.

Important

You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite. But G Suite or Google Workspace administrator must authorize service account in Google Admin Console to access user mailbox.

Create service account in current project

  • Click "Credentials" -> "Manage service accounts"

    manage service account in google developers console
  • Click "CREATE SERVICE ACCOUNT"

    create service account in google developers console
  • Input a name for your service account, click "DONE"

After service account is created, you should enable "Domain-wide delegation" and create service key pair to access G Suite or Google Workspace user mailbox.

Create service key

  • Go back to your service account -> Keys, click Add Key, you can select "p12" or "json" key type, both can work well, then you will get a file which contains private key, save the file to local disk.

    Now you have created service account with key pair successfully. You can use created private key in your codes to request "access token" impersonating a user in G Suite or Google Workspace.

create service key
  • To access user data in G Suite, you must get authorization from G Suite or Google Workspace administrator. You should go back to your service account -> Details, copy your service account email address and client id.
google oauth client id

Enable Gmail API

Enable Gmail API in "Library" -> Search "Gmail", then click "Gmail API" and enable it. If you use Gmail API protocol to send email, you should enable this API, if you use SMTP protocol, you don’t have to enable it.

enable Gmail API

Authorize service account by G Suite administrator

To use service account to access user mailbox in G Suite or Google Workspace, G Suite Administrator should authorize specified service account at first.

Important

Important Notice: You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite or Google Workspace. But G Suite or Google Workspace administrator must authorize service account in G Suite or Google Workspace Admin Console to access user mailbox.

  • The administrator should open admin.google.com, go to Admin Console, click "Security" > API Control;

    Authorize Service Account by G Suite Administrator
  • In the Domain wide delegation pane, select Manage Domain Wide Delegation.

  • Click Add new.

  • In the Client ID field, enter the service account’s Client ID

  • Click Add new and enter your service account client ID.

  • Enter the client ID of the service account or OAuth2 client ID of the app.

  • In the OAuth scopes (comma-delimited) field, enter the list of scopes that your application should be granted access to. and input https://mail.google.com/, email, profile in One or More API Scopes, click "Authorize".

manage api client access by G Suite Administrator 1
  • Click Authorize.

After the administrator authorized service account, you can use it to access any users mailbox in G Suite or Google Workspace domain.

Learn more detail from: https://developers.google.com/identity/protocols/oauth2/service-account

Enable TLS Strong Encryption Algorithms in .NET 2.0 and .NET 4.0

Because HttpWebRequest is used to get access token from web service. If you’re using .NET framework (.NET 2.0 - 3.5 and .NET 4.x), you need to enable Strong Encryption Algorithms to request access token:

Put the following content to a file named NetStrongEncrypt.reg, right-click this file -> Merge -> Yes. You can also download it from https://www.emailarchitect.net/webapp/download/NetStrongEncrypt.zip.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

Access token lifetime

You don’t have to request access token every time. By default, access token expiration time is 3600 seconds, you can reuse the access token repeatedly before it is expired.

Delphi - Send email using Gmail/G Suite OAuth 2.0 with service account - example

const
    ConnectNormal = 0;
    ConnectSSLAuto = 1;
    ConnectSTARTTLS = 2;
    ConnectDirectSSL = 3;
    ConnectTryTLS = 4;

    AuthAuto = -1;
    AuthLogin = 0;
    AuthNtlm = 1;
    AuthCramMd5 = 2;
    AuthPlain = 3;
    AuthMsn = 4;
    AuthXoauth2 = 5;

    CRYPT_MACHINE_KEYSET = 32;
    CRYPT_USER_KEYSET = 4096;

function TForm1.RequestAccessToken(requestData: WideString): WideString;
var
    httpRequest: TServerXMLHTTP;
    oauthParser: TOAuthResponseParser;
    fullRequest: OleVariant;
    status: integer;
    responseText: WideString;
    accessToken: WideString;
begin
    result := '';
    httpRequest := TServerXMLHTTP.Create(Application);

    fullRequest := 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=';
    fullRequest := fullRequest + requestData;

    httpRequest.setOption(2, 13056);
    httpRequest.open('POST', 'https://oauth2.googleapis.com/token', true);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send(fullRequest);

    while( httpRequest.readyState <> 4 ) do
    begin
        try
            httpRequest.waitForResponse(1);
            Application.ProcessMessages();
        except
            ShowMessage('Server response timeout (access token).');
            exit;
        end;
    end;

    status := httpRequest.status;
    responseText := httpRequest.responseText;

    if (status < 200) or (status >= 300) then
    begin
        ShowMessage('Failed to get access token from server.' + responseText);
        exit;
    end;

    oauthParser := TOAuthResponseParser.Create(Application);
    oauthParser.Load(responseText);

    accessToken := oauthParser.AccessToken;

    if accessToken = '' then
    begin
        ShowMessage('Failed to parse access token from server response.');
        exit;
    end;

    result := accessToken;
end;

function TForm1.GenerateRequestData(gsuiteUser: WideString): WideString;
const
    // service account email address
    serviceAccount: WideString = 'xxxx@xxxx.iam.gserviceaccount.com';
    scope: WideString = 'https://mail.google.com/';
    aud: WideString = 'https://oauth2.googleapis.com/token';
var
    jwt: TSimpleJsonParser;
    cert: TCertificate;
    pfxPath: WideString;
    header: WideString;
    playload: WideString;
    signature: WideString;
    iat, exp: integer;
begin
    result := '';

    SetThreadLocale(GetSystemDefaultLCID());

    jwt := TSimpleJsonParser.Create(application);

    header := jwt.JwtBase64UrlEncode('{"alg":"RS256","typ":"JWT"}');

    // token request timestamp
    iat := jwt.GetCurrentIAT();
    // token expiration time
    exp := iat + 3600;

    playload := '{';
    playload := playload + '"iss":"' + serviceAccount + '",';
    playload := playload + '"scope":"' + scope + '",';
    playload := playload + '"aud":"' + aud + '",';
    playload := playload + '"exp":' + IntToStr(exp) + ',';
    playload := playload + '"iat":' + IntToStr(iat) + ',';
    playload := playload + '"sub":"' + gsuiteUser + '"';
    playload := playload + '}';

    playload := jwt.JwtBase64UrlEncode(playload);

    cert := TCertificate.Create(application);

    // load service account certificate to sign request data
    pfxPath := 'D:\MyData\GSuite\outh-77aec4d192ec.p12';
    if not cert.LoadPFXFromFile(pfxPath, 'notasecret', CRYPT_USER_KEYSET) then
        begin
            ShowMessage('Failed to load certificate!');
            exit;
        end;

    signature := jwt.SignRs256(cert.DefaultInterface, header + '.' + playload);
    if signature = '' then
        begin
            ShowMessage('Failed to sign request data!');
            exit;
        end;

    result := header + '.' + playload + '.' + signature;
end;

procedure TForm1.SendEmail();
var
    oSmtp : TMail;
    gsuiteUser, accessToken: WideString;
begin
    // request access token with service account
    // gsuiteUser is the full email address of the user in GSuite, for example: user@gsuitedomain
    gsuiteUser := 'user@gsuitedomain.com'
    accessToken := RequestAccessToken(GenerateRequestData(gsuiteUser));
    if accessToken = '' then
        exit;

    oSmtp := TMail.Create(Application);
    oSmtp.LicenseCode := 'TryIt';

    // Gmail SMTP server address
    oSmtp.ServerAddr := 'smtp.gmail.com';
    oSmtp.ServerPort := 587;

    // Enable SSL/TLS connection
    oSmtp.ConnectType := ConnectSSLAuto;

    // Gmail OAUTH type
    oSmtp.AuthType := AuthXoauth2;
    oSmtp.UserName := email;
    oSmtp.Password := accessToken;

    // Set sender email address
    oSmtp.FromAddr := email;

    // Add recipient email address
    oSmtp.AddRecipientEx('support@emailarchitect.net', 0);

    // Set email subject
    oSmtp.Subject := 'simple email from Delphi project';

    // Set email body
    oSmtp.BodyText := 'this is a test email sent from Delphi project, do not reply';

    ShowMessage('start to send email ...');

    if oSmtp.SendMail() = 0 then
        ShowMessage('email was sent successfully!')
    else
        ShowMessage('failed to send email with the following error: '
        + oSmtp.GetLastErrDescription());

end;

end.

EA Oauth Service for Gmail

If your code is too complex or out of maintenance, and you don’t want to change anything in your source codes, then you can have a try with EA Oauth Service for Gmail. It provides an easy way for the legacy email application that doesn’t support OAUTH 2.0 to send and retrieve email from Gmail without changing any codes. SMTP, POP, IMAP and SSL/TLS protocols are supported.

TLS 1.2 protocol

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.