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, 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 email service without user interaction. Service account only works for G Suite user, it doesn’t work for personal Gmail account.

Create Project in Google Developers Console

To use “G Suite Service Account OAuth” in your application, you should create a project in Google Developers 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 administrator must authorize service account in G Suite 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 "CREATE"

    create service account in google developers console step 1
  • In "Service account permissions", select "Project" -> "Owner" as role

    create service account in google developers console step 2
  • In "Grant users access to this service account", keep everything default and click "DONE"

    create service account in google developers console step 3

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

Enable “Domain-wide delegation” and Create Service Key

  • Go back to your service account, click "Edit" -> "SHOW DOMAIN-WIDE DELEGATION", check "Enable G Suite Domain-wide Delegation", input a name for product oauth consent, click "Save".

    Enable G Suite Domain-wide Delegation
  • Go back to your service account again, click "Create 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.

    create service key
  • To access user data in G Suite, you must get authorization from G Suite administrator. You should go to service accounts list, click "View Client ID" like this:

    google oauth client id
  • Then copy your “Client ID” and service account email address, forward it to G Suite administrator for authorization.

    google oauth serivce 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, 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. But G Suite administrator must authorize service account in G Suite Admin Console to access user mailbox.

  • G Suite Administrator should open admin.google.com, go to Admin Console, click "Security";

    Authorize Service Account by G Suite Administrator
  • Click "Advanced settings" -> "Manage API client access";

    manage api client access by G Suite Administrator
  • Input service account "Client ID" in Client Name, and input "https://mail.google.com/,email,profile" in One or More API Scopes, click "Authorize".

    If you use Gmail API protocol instead of SMTP protocol, input: "https://www.googleapis.com/auth/gmail.send,email,profile".

    manage api client access by G Suite Administrator 1

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

Important

You should create your client id and client secret, do not use the client id from example codes in production environment, it is used for test purpose.

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.

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.