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
We enter the password for our account.
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.
Next, select Enabled APIs & services.
Now, click on CREATE PROJECT.
Next, enter the project name and click CREATE.
Afterward, click ENABLE APIS AND SERVICES.
Click on the Gmail API tab.
Now we need to allow the use of the Gmail API. To do this, click ENABLE.
We select User Type External and click CREATE (on the OAuth consent screen tab).
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).
We also enter Developer contact information (here we enter the user’s email address) and click SAVE AND CONTINUE.
Next, we leave everything as default and click SAVE AND CONTINUE.
Now click BACK TO DASHBOARD.
Click PUBLISH APP.
Here, just click CONFIRM.
Next, click on ‘Credentials’. Then select CREATE CREDENTIALS.
Next, select OAuth client ID.
Then select the application type (Web Application) and also enter the application name.
Also, for the API to work properly, it is necessary to add a redirect URL. To do this, click on ADD URI.
Now add https://developers.google.com/oauthplayground and click CREATE.
In this window, we can copy the Client ID and Client secret. Save them for future use.
Next, go to https://developers.google.com/oauthplayground/. Then enter the link https://mail.google.com and open the settings.
Paste the previously saved Client ID and Client secret, then click Close.
Then click Authorize APIs.
Next, select your Google account.
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.
Next, choose to proceed to the link in the application (unsafe as it has not been verified by Google experts). Feel free to continue!
Then just click Continue.
On the page that appears, click Exchange authorization code for tokens.
Next, copy the Access token for further use in our Embarcadero Delphi FMX application.
Note! The token expires after a certain period of time! Once it expires, you need to refresh the token and copy it again for use in our Delphi application.
To work with the Gmail API, we have developed a special class called TGmailAPIHelper.
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).
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.
To input the sender’s address, recipient’s address, and email subject, we use the TEdit component.
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.
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.
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.
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.
As a result of the application’s operation, we receive an email in our Gmail account.