• Blog
  • How to Send Email via Embarcadero Delphi FMX App by Using Gmail API

How to Send Email via Embarcadero Delphi FMX App by Using Gmail API

Guide on using the Gmail API to send messages

Publish date:
Discover more of what matters to you

Today, there are many different email services available. They are used for official business correspondence in companies, institutions, and more. One of the most popular email services is Gmail by Google. To use it, all you need to do is register and create an email account (simply follow this link: https://mail.google.com). Nowadays, almost everyone has a registered Google account (and thus a Gmail email).

However, the standard features of the Gmail web interface, such as sending, reading, and deleting messages, are not always sufficient. Therefore, Gmail also provides an API, allowing us to implement functionalities for sending messages, deleting them, and more in our applications.

In this article, we will walk you through how to use the Gmail API to send messages from our Embarcadero Delphi FMX application, step by step.

To start, we need to go to the Google Cloud Console at this link.

https://console.cloud.google.com

Sending email in Delphi FMX using Gmail API
Delphi FMX app integration with Gmail API for email sending

We enter the password for our account.

Tutorial on sending email from Delphi FMX with Gmail API

Now, you need to select your country and check the box for “Terms of Service” and optionally “Email Updates” if you’d like to receive news and other information from Google.

How to connect Gmail API with Delphi FMX for email

Next, select Enabled APIs & services.

Steps to send email in Delphi FMX using Gmail API
Using Gmail API to send emails from Delphi FMX app

Now, click on CREATE PROJECT.

Guide to emailing via Gmail API in Embarcadero Delphi

Next, enter the project name and click CREATE.

Send emails through Delphi FMX with Gmail API

Afterward, click ENABLE APIS AND SERVICES.

Setting up Gmail API in Delphi FMX for email functionality

Click on the Gmail API tab.

How to implement email sending in Delphi FMX with Gmail

Now we need to allow the use of the Gmail API. To do this, click ENABLE.

Email integration in Delphi FMX app using Gmail API

We select User Type External and click CREATE (on the OAuth consent screen tab).

Gmail API email sending tutorial for Delphi FMX apps

Next, we enter the name of our application in App name and the user support email in User support email (the email from which messages will be sent).

Connecting Delphi FMX with Gmail API for email

We also enter Developer contact information (here we enter the user’s email address) and click SAVE AND CONTINUE.

Using Gmail API in Delphi to send email messages
Step-by-step guide to email sending in Delphi FMX

Next, we leave everything as default and click SAVE AND CONTINUE.

How to use Gmail API for sending emails from Delphi
Implementing Gmail API for email in Embarcadero Delphi FMX
Email feature setup in Delphi FMX app with Gmail API

Now click BACK TO DASHBOARD.

Delphi FMX Gmail API email sending instructions

 Click PUBLISH APP.

How to configure Gmail API in Delphi for emailing

Here, just click CONFIRM.

Integrating Gmail API for email functionality in Delphi FMX

Next, click on ‘Credentials’. Then select CREATE CREDENTIALS.

Guide to email setup in Delphi FMX with Gmail API

Next, select OAuth client ID.

How to enable email sending in Delphi FMX via Gmail

Then select the application type (Web Application) and also enter the application name.

Email communication in Delphi FMX using Gmail API

Also, for the API to work properly, it is necessary to add a redirect URL. To do this, click on ADD URI.

Creating email functionality in Delphi apps with Gmail API

Now add https://developers.google.com/oauthplayground and click CREATE.

Gmail API email integration tutorial for Delphi developers

In this window, we can copy the Client ID and Client secret. Save them for future use.

Step-by-step setup of Gmail API for Delphi FMX email
Delphi FMX Gmail API guide for email messaging

Next, go to https://developers.google.com/oauthplayground/. Then enter the link https://mail.google.com and open the settings.

Sending emails from Embarcadero Delphi FMX via Gmail

Paste the previously saved Client ID and Client secret, then click Close.

Using Gmail API for Delphi FMX app email solutions

Then click Authorize APIs.

Configuring Gmail API email service in Delphi FMX app

Next, select your Google account.

How to send automated emails from Delphi FMX using Gmail

After that, we will see a warning that our application has not been verified by Google. To use our application without verification by Google experts, simply follow the instructions in the images below.

Select Advanced.

Detailed guide to Gmail API email in Delphi FMX

Next, choose to proceed to the link in the application (unsafe as it has not been verified by Google experts). Feel free to continue!

Sending Gmail emails directly from Delphi FMX application

Then just click Continue.

Using Gmail API for secure email sending in Delphi

On the page that appears, click Exchange authorization code for tokens.

Tutorial on Gmail API integration for Delphi email

Next, copy the Access token for further use in our Embarcadero Delphi FMX application.

Adding Gmail email support to Delphi FMX applications

To work with the Gmail API, we have developed a special class called TGmailAPIHelper.

Delphi FMX app tutorial for Gmail API email setup

This class contains a constructor that accepts an object of the TNetHttpClient class and a string constant AccessToken, which holds the secret key that we saved earlier for future use.

The SendEmail method takes string constants as parameters: FromEmail, ToEmail, Subject, and EmailMessage, which represent the sender’s address, recipient’s address, email subject, and the message itself, respectively.

FNetHttpClient takes the URL for sending a POST request with the sender’s address, recipient’s address, email subject, and the message itself via the Gmail API. It also accepts headers and two objects – ResponseContent and StringStream.

The string variable Request contains the text of the request (sender’s address, recipient’s address, email subject, and the message) to be sent to the recipient via the Gmail API. The objects ResponseContent and StringStream of the TStringStream class hold the JSON response from the Gmail API as a string and the request text for sending to the recipient, respectively.

The dynamic array Headers contains the headers for the Access Token (Authorization parameter), which we obtained earlier, and the content type (Content-Type parameter). In our case, the content type is message/rfc822.

The SendEmail method returns the JSON response from the Gmail API as a string (type string).

Delphi FMX app tutorial for Gmail API email setup

The source code for the TGmailAPIHelper class is provided below:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
unit GmailAPI;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics,
FMX.Dialogs, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls,
FMX.Controls.Presentation, System.Net.URLClient, System.Net.HttpClient,
System.Net.HttpClientComponent, JSON, System.Threading,
System.Net.Mime, System.Generics.Collections;
type
IGmailAPIHelper = interface
function SendEmail(const FromEmail: string; const ToEmail: string;
const Subject: string; const EmailMessage: string): string;
end;
TGmailAPIHelper = class(TInterfacedObject, IGmailAPIHelper)
private
FNetHttpClient: TNetHTTPClient;
FAccessToken: string;
public
function SendEmail(const FromEmail: string; const ToEmail: string;
const Subject: string; const EmailMessage: string): string;
constructor Create(const NetHttpClient: TNetHTTPClient;
const AccessToken: string);
end;
implementation
{ TGmailAPIHelper }
constructor TGmailAPIHelper.Create(const NetHttpClient: TNetHTTPClient;
const AccessToken: string);
begin
FNetHttpClient := NetHttpClient;
if AccessToken <> '' then
FAccessToken := AccessToken
else
begin
ShowMessage('Access token is empty!');
Exit;
end;
end;
function TGmailAPIHelper.SendEmail(const FromEmail, ToEmail, Subject,
EmailMessage: string): string;
var
Headers: TArray<TNameValuePair>;
Request: string;
ResponseContent, StringStream: TStringStream;
begin
ResponseContent := nil;
StringStream := nil;
try
SetLength(Headers, 2);
Headers[0] := TNameValuePair.Create('Authorization', FAccessToken);
Headers[1] := TNameValuePair.Create('Content-Type', 'message/rfc822');
Request := 'From: ' + FromEmail + #13#10 +
'To: ' + ToEmail + #13#10 + 'Subject: ' + Subject + #13#10 + #13#10 +
EmailMessage + '.';
StringStream := TStringStream.Create(Request, TEncoding.ASCII);
ResponseContent := TStringStream.Create;
FNetHttpClient.Post(
'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send',
StringStream, ResponseContent, Headers);
Result := ResponseContent.DataString;
finally
ResponseContent.Free;
StringStream.Free;
end;
end;
end.

Let’s consider our Embarcadero Delphi FMX application. To make a POST request to the Gmail API for the purpose of sending an email to the recipient, we use the TNetHttpClient component.

How Delphi FMX apps can send emails via Gmail API

To input the sender’s address, recipient’s address, and email subject, we use the TEdit component.

Setting up secure Gmail API email in Delphi FMX apps

We use the TMemo component to input the text of the email and to display the JSON response from the Gmail API as a string.

Step-by-step email sending with Gmail API in Delphi

The email sending to the recipient is implemented in the click handler of the ‘OK’ button (the TButton component). To pass the token, we will declare a text field FAccessToken in the OnCreate method of the main form.

Using Delphi FMX for Gmail API email automation

In the click handler of the button, we will declare an object GmailHelper of the class TGmailAPIHelper. We will also declare a string variable Response that will contain the JSON response from the Gmail API.

To prevent blocking the main thread of the application while executing the request to the Gmail API, we use TTask.Run. We call the constructor of the TGmailAPIHelper class and pass NetHttpClient1 and FAccessToken as input parameters. Next, we call the SendEmail method. The JSON response from the Gmail API will be displayed in the Memo2 field.

Enabling Gmail API emails in a Delphi FMX app

The complete code for the module Main.pas is provided below:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types,
{$IFDEF ANDROID}
AndroidApi.Helpers, FMX.Platform.Android, Androidapi.JNI.Widget, FMX.Helpers.Android,
System.IOUtils, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net,
Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge,
{$ENDIF}
FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, GmailAPI,
System.Net.URLClient, System.Net.HttpClient, System.Threading, System.Net.HttpClientComponent;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
Label2: TLabel;
EditFrom: TEdit;
Label3: TLabel;
Memo1: TMemo;
Button1: TButton;
EditTo: TEdit;
Label4: TLabel;
NetHTTPClient1: TNetHTTPClient;
Label5: TLabel;
EditSubject: TEdit;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FAccessToken: string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
var
GmailHelper: TGmailAPIHelper;
Response: string;
begin
TTask.Run(
procedure
begin
GmailHelper := TGmailAPIHelper.Create(NetHTTPClient1, 'Bearer ' + FAccessToken);
try
Response := GmailHelper.SendEmail(EditFrom.Text, EditTo.Text, EditSubject.Text,
Memo1.Text);
TThread.Synchronize(nil,
procedure
begin
Memo2.Text := Response;
end);
finally
GmailHelper.Free;
end;
end);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FAccessToken := 'ya29.a0AeDClZAoe05nsEGZxvud5UE7IarkGTLlY61cnMiMj3ixuzFH1htlWfJNzY3Tt0AZiPeQGmQde_TOj9ZUrO5eFezx8HKGZcd-NNGUi7j3tcVr8l94U5YL_THnXPc8sD4aym6p2Ms8zu2yAlc86Lg30tRUeukIqIRpYq3mFZZ7aCgYKAV4SARISFQHGX2MizAMnKQOWggzKHi0H2bdmSg0175';
end;
end.

Now let’s test the functionality of our Embarcadero Delphi FMX application.

Guide to Gmail API setup for Delphi FMX emails

As a result of the application’s operation, we receive an email in our Gmail account.

Integrating Gmail with Delphi FMX for email delivery
Delphi Development Services
We handle Delphi migration, integration, and development, fully sharing project risks and responsibilities.
Learn more

Subscribe to our newsletter and get amazing content right in your inbox.

This field is required
This field is required Invalid email address
By submitting data, I agree to the Privacy Policy

Thank you for subscribing!
See you soon... in your inbox!

confirm your subscription, make sure to check your promotions/spam folder

Subscribe to our newsletter and get amazing content right in your inbox.

You can unsubscribe from the newsletter at any time

This field is required
This field is required Invalid email address

You're almost there...

A confirmation was sent to your email

confirm your subscription, make sure to check
your promotions/spam folder