The Gmail/GSuite IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Gmail Web OAuth instead of inputting user and password directly in application.
You can click here to learn more detail about "OAUTH/XOAUTH2 with Gmail SMTP Server".
Normal OAUTH requires user input user/password for authentication. 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 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.
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 record your "Client ID" and service account email address, forward it to G Suite administrator for authorization.
To use service account to access user mailbox in G Suite, G Suite Administrator should authorize specified service account at first. >
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;
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://www.googleapis.com/auth/gmail.send,email,profile".
After G Suite administrator authorized service account, you can use it to access any users mailbox in G Suite domain.
The following examples demonstrate how to send email with service account + G Suite OAUTH
Example
[VB6 - Use service account to send email impersonating user in G Suite Domain] Const ConnectNormal = 0 Const ConnectSSLAuto = 1 Const ConnectSTARTTLS = 2 Const ConnectDirectSSL = 3 Const ConnectTryTLS = 4 Const AuthAuto = -1 Const AuthLogin = 0 Const AuthNtlm = 1 Const AuthCramMd5 = 2 Const AuthPlain = 3 Const AuthMsn = 4 Const AuthXoauth2 = 5 Const CRYPT_MACHINE_KEYSET = 32 Const CRYPT_USER_KEYSET = 4096 Private Function GenerateRequestData(GsuiteUser) GenerateRequestData = "" ' service account email address Const serviceAccount = "xxxxxx@xxxxxx.iam.gserviceaccount.com" Const scope = "https://mail.google.com/" Const aud = "https://oauth2.googleapis.com/token" Dim jwt As New EASendMailObjLib.SimpleJsonParser Dim header, playload header = jwt.JwtBase64UrlEncode("{""alg"":""RS256"",""typ"":""JWT""}") Dim iat, exp ' 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"":" & exp & "," playload = playload & """iat"":" & iat & "," playload = playload & """sub"":""" & gsuiteUser & """" playload = playload & "}" playload = jwt.JwtBase64UrlEncode(playload) Dim cert As New EASendMailObjLib.Certificate ' In web application, use CRYPT_MACHINE_KEYSET If Not cert.LoadPFXFromFile("D:\myfolder\myoauth-77dec4d192ec.p12", "notasecret", CRYPT_USER_KEYSET) Then MsgBox "Failed to load service account certificate!" Exit Function End If Dim signature signature = jwt.SignRs256(cert, header & "." & playload) If signature = "" Then MsgBox "Failed to sign request data!" Exit Function End If Dim dataToPost dataToPost = header & "." & playload & "." & signature GenerateRequestData = dataToPost End Function Private Function RequestAccessToken(requestData) RequestAccessToken = "" If requestData = "" Then Exit Function End If On Error GoTo ErrorHandle Dim httpRequest Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP") requestData = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" & 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 requestData Do While httpRequest.ReadyState <> 4 DoEvents httpRequest.waitForResponse (1) Loop Dim Status Status = httpRequest.Status If Status < 200 Or Status >= 300 Then MsgBox "Failed to get access token from server." MsgBox httpRequest.responseText Exit Function End If Dim result result = httpRequest.responseText Dim oauthParser As New EASendMailObjLib.OAuthResponseParser oauthParser.Load result Dim accessToken accessToken = oauthParser.AccessToken If accessToken = "" Then MsgBox "Failed to parse access token from server response." Exit Function End If RequestAccessToken = accessToken Exit Function ErrorHandle: MsgBox "Failed to request access token." & Err.Description End Function Private Sub SendEmail(GsuiteUser As String) ' GsuiteUser is the full email address of the user in GSuite, user@gsuitedomain Dim access_token As String ' request access token from Google server by service account ' withou user interaction access_token = RequestAccessToken(GenerateRequestData(GsuiteUser)) If access_token = "" Then Exit Sub End If Dim oSmtp As EASendMailObjLib.Mail Set oSmtp = New EASendMailObjLib.Mail oSmtp.LicenseCode = "TryIt" oSmtp.ServerAddr = "smtp.gmail.com" oSmtp.ServerPort = 587 ' Enable SSL/TLS connection oSmtp.ConnectType = ConnectSSLAuto ' Gmail OAUTH/XOAUTH2 type oSmtp.AuthType = AuthXoauth2 oSmtp.UserName = GsuiteUser oSmtp.Password = access_token oSmtp.FromAddr = GsuiteUser oSmtp.AddRecipient "Support Team", "support@emailarchitect.net", 0 oSmtp.BodyText = "Hello, this is a test...." If oSmtp.SendMail() = 0 Then MsgBox "Message delivered!" Else MsgBox oSmtp.GetLastErrDescription() End If End Sub
[Visual C++ - Use service account to send email impersonating user in G Suite Domain] #include "pch.h" #include <tchar.h> #include <Windows.h> #include "EASendMailObj.tlh" using namespace EASendMailObjLib; #include "msxml3.tlh" using namespace MSXML2; const int ConnectNormal = 0; const int ConnectSSLAuto = 1; const int ConnectSTARTTLS = 2; const int ConnectDirectSSL = 3; const int ConnectTryTLS = 4; const int AuthAuto = -1; const int AuthLogin = 0; const int AuthNtlm = 1; const int AuthCramMd5 = 2; const int AuthPlain = 3; const int AuthMsn = 4; const int AuthXoauth2 = 5; BOOL RequestAccessToken(const TCHAR* requestData, _bstr_t &accessToken) { try { IServerXMLHTTPRequestPtr httpRequest = NULL; httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP)); if (httpRequest == NULL) { _tprintf(_T("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n")); return FALSE; } _bstr_t fullRequest = _bstr_t("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=") + requestData; const char* postData = (const char*)fullRequest; LONG cdata = strlen(postData); LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL); for (LONG k = 0; k < (int)cdata; k++) { BYTE ch = (BYTE)postData[k]; ::SafeArrayPutElement(psaHunk, &k, &ch); } _variant_t requestBuffer; requestBuffer.vt = (VT_ARRAY | VT_UI1); requestBuffer.parray = psaHunk; _variant_t async(true); _bstr_t uri(_T("https://oauth2.googleapis.com/token")); httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056); httpRequest->open(L"POST", uri, async, vtMissing, vtMissing); httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded"); httpRequest->send(requestBuffer); while (httpRequest->readyState != 4) { httpRequest->waitForResponse(1); } long status = httpRequest->status; _bstr_t responseText = httpRequest->responseText; if (status < 200 || status >= 300) { _tprintf(_T("Failed to get access token from server: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } IOAuthResponseParserPtr oauthParser = NULL; oauthParser.CreateInstance(__uuidof(EASendMailObjLib::OAuthResponseParser)); oauthParser->Load(responseText); accessToken = oauthParser->AccessToken; if (accessToken.length() == 0) { _tprintf(_T("Failed to parse access token from server response: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } return TRUE; } catch (_com_error &ep) { _tprintf(_T("Failed to get access token: %s"), (const TCHAR*)ep.Description()); return FALSE; } } BOOL GenerateRequestData(const TCHAR* gsuiteUser, _bstr_t &requestData) { // service account email address const TCHAR* serviceAccount = _T("xxxx@xxxx.iam.gserviceaccount.com"); const TCHAR* scope = _T("https://mail.google.com/"); const TCHAR* aud = _T("https://oauth2.googleapis.com/token"); ISimpleJsonParserPtr jwtPtr = NULL; jwtPtr.CreateInstance(__uuidof(EASendMailObjLib::SimpleJsonParser)); _bstr_t header = jwtPtr->JwtBase64UrlEncode(_T("{\"alg\":\"RS256\",\"typ\":\"JWT\"}")); // token request timestamp long iat = jwtPtr->GetCurrentIAT(); // token expiration time long exp = iat + 3600; TCHAR iatBuf[MAX_PATH + 1]; TCHAR expBuf[MAX_PATH + 1]; _stprintf_s(iatBuf, MAX_PATH, _T("%d"), iat); _stprintf_s(expBuf, MAX_PATH, _T("%d"), exp); _bstr_t playload = _bstr_t("{"); playload += _bstr_t("\"iss\":\"") + _bstr_t(serviceAccount) + _bstr_t("\","); playload += _bstr_t("\"scope\":\"") + _bstr_t(scope) + _bstr_t("\","); playload += _bstr_t("\"aud\":\"") + _bstr_t(aud) + _bstr_t("\","); playload += _bstr_t("\"exp\":") + _bstr_t(expBuf) + _bstr_t(","); playload += _bstr_t("\"iat\":") + _bstr_t(iatBuf) + _bstr_t(","); playload += _bstr_t("\"sub\":\"") + _bstr_t(gsuiteUser) + _bstr_t("\""); playload += _bstr_t("}"); playload = jwtPtr->JwtBase64UrlEncode(playload); ICertificatePtr cert = NULL; cert.CreateInstance(__uuidof(EASendMailObjLib::Certificate)); // In web application, use CRYPT_MACHINE_KEYSET if (cert->LoadPFXFromFile(_T("D:\\MyData\\oauth-77dac4d192ec.p12"), _T("notasecret"), CRYPT_USER_KEYSET) == VARIANT_FALSE) { _tprintf(_T("Failed to load service account certificate!")); return FALSE; } _bstr_t signature = jwtPtr->SignRs256(cert, header + _bstr_t(".") + playload); if (signature.length() == 0) { _tprintf(_T("Failed to sign request data!")); return FALSE; } requestData = header + _bstr_t(".") + playload + _bstr_t(".") + signature; return TRUE; } void SendEmail(const TCHAR* gsuiteUser) { ::CoInitialize(NULL); // gsuiteUser is the full email address of the user in GSuite, for example: user@gsuitedomain _bstr_t requestData, accessToken; if (!GenerateRequestData(gsuiteUser, requestData)) { return; } // request access token from Google server by service account // withou user interaction if (!RequestAccessToken((const TCHAR*)requestData, accessToken)) { return; } IMailPtr oSmtp = NULL; oSmtp.CreateInstance(__uuidof(EASendMailObjLib::Mail)); oSmtp->LicenseCode = _T("TryIt"); oSmtp->ServerAddr = _T("smtp.gmail.com"); oSmtp->ServerPort = 587; // Enable SSL/TLS connection oSmtp->ConnectType = ConnectSSLAuto; // Gmail OAUTH type oSmtp->AuthType = AuthXoauth2; oSmtp->UserName = gsuiteUser; oSmtp->Password = accessToken; oSmtp->FromAddr = gsuiteUser; oSmtp->AddRecipient(_T("Support Team"), _T("support@emailarchitect.net"), 0); oSmtp->BodyText = _T("Hello, this is a test...."); if (oSmtp->SendMail() == 0) _tprintf(_T("Message delivered!")); else _tprintf((const TCHAR*)oSmtp->GetLastErrDescription()); }
[Delphi - Use service account to send email impersonating user in G Suite Domain] 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(gsuiteUser: string); var oSmtp : TMail; accessToken: WideString; begin // request access token with service account // gsuiteUser is the full email address of the user in GSuite, for example: user@gsuitedomain 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.
Remarks
You don't have to request access token every time, once you get an access token, it is valid within 3600 seconds.
If you don't want to use OAUTH 2.0, Gmail also supports traditional ESMTP authentication, but you need to enable Allowing less secure apps or Sign in using App Passwords.
Remarks
If you don't want to use OAUTH 2.0, Gmail also supports traditional ESMTP authentication, but you need to enable Allowing less secure apps or Sign in using App Passwords.
Online Example
VB6 - Send Email using Google/Gmail
OAuth 2.0
Authentication
VB6 - Send Email using Gmail/G Suite
OAuth
2.0 in Background Service (Service Account)
VB6 - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) from Hotmail/Outlook Account
VB6 - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
VB6 - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
Delphi - Send Email using Google/Gmail
OAuth 2.0
Authentication
Delphi - Send Email using Gmail/G Suite
OAuth
2.0 in Background Service (Service Account)
Delphi - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) from Hotmail/Outlook Account
Delphi - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
Delphi - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
Visual C++ - Send Email using
Google/Gmail
OAuth 2.0
Authentication
Visual C++ - Send Email using Gmail/G
Suite OAuth
2.0 in Background Service (Service Account)
Visual C++ - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) from Hotmail/Outlook Account
Visual C++ - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
Visual C++ - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
See Also
Using EASendMail ActiveX Object
Registration-free COM with Manifest File
User Authentication and SSL Connection
Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2
Using Gmail SMTP OAUTH
Using Office365 EWS OAUTH
Using Office365 EWS OAUTH in Background Service
Using Hotmail SMTP OAUTH
From, ReplyTo, Sender and Return-Path
Digital Signature and Email Encryption - S/MIME
DomainKeys Signature and DKIM Signature
Send Email without SMTP server(DNS lookup)
Work with EASendMail Service(Mail Queuing)
Programming with Asynchronous Mode
Programming with FastSender
Mail vs. FastSender
Bulk Email Sender Guidelines
Process Bounced Email (Non-Delivery Report) and Email Tracking
Work with RTF and Word
EASendMail ActiveX Object References
EASendMail SMTP Component Samples