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.
Sections:
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.
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.
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.
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.
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.
Open Google Developer Console, create a new project by https://console.developers.google.com/projectcreate.
After you created the project, select it from projects list as current project.
Click "Credentials"
-> "Manage service accounts"
Click "CREATE SERVICE ACCOUNT"
Input a name for your service account, click "CREATE"
In "Service account permissions"
, select "Project"
-> "Owner"
as role
In "Grant users access to this service account"
, keep everything default and click "DONE"
After service account is created, you should enable "Domain-wide delegation"
and create service key pair
to access G Suite user mailbox.
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"
.
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.
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:
Then copy your “Client ID” and service account email address, forward it to G Suite administrator for authorization.
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.
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"
> API Control
;
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 OAuth Scopes, add each scope that the application can access (should be appropriately narrow).
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://mail.google.com/
, email
, profile
.
After G Suite administrator authorized service account, you can use it to access any users mailbox in G Suite domain.
Because HttpWebRequest is used to get access token from web service.
If you’re using legacy .NET framework (.NET 2.0 and .NET 4.0),
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
You don’t have to request access token
every time. By default,
access token
expiration time is 3600 seconds, you can use the access token
repeatedly before it is expired.
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. If you got "This app isn't verified"
information, please click "Advanced"
-> Go to ...
for test.
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 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.