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
[C# - Use service account to send email impersonating user in G Suite Domain] // You can install Google.Apis.Auth.OAuth2 by NuGet // Install-Package Google.Apis.Auth using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using Google.Apis.Auth.OAuth2; using EASendMail; public void SendMail() { try { // service account email address const string serviceAccount = "xxxxxx@xxxxx.iam.gserviceaccount.com"; // import service account key p12 certificate. var certificate = new X509Certificate2("D:\\MyData\\myoauth-77dec4d192ec.p12", "notasecret", X509KeyStorageFlags.Exportable); // G Suite user email address var gsuiteUser = "user@gsuitdomain.com"; var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount) { User = gsuiteUser, Scopes = new[] { "https://mail.google.com/"} }.FromCertificate(certificate); // if service account key is in json format, copy the private key from json file: // "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" // and import it like this: // string privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEv...revdd\n-----END PRIVATE KEY-----\n"; // var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount) //{ // User = gsuiteUser, // Scopes = new[] { "https://mail.google.com/" } // }.FromPrivateKey(privateKey); // request access token var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer); if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result) throw new InvalidOperationException("Access token failed."); var server = new SmtpServer("smtp.gmail.com 587"); server.ConnectType = SmtpConnectType.ConnectSSLAuto; server.User = gsuiteUser; server.Password = credential.Token.AccessToken; server.AuthType = SmtpAuthType.XOAUTH2; var mail = new SmtpMail("TryIt"); mail.From = gsuiteUser; mail.To = "support@emailarchitect.net"; mail.Subject = "service account oauth test"; mail.TextBody = "this is a test, don't reply"; var smtp = new SmtpClient(); smtp.SendMail(server, mail); Console.WriteLine("Message delivered!"); } catch (Exception ep) { Console.WriteLine(ep.ToString()); } }
[VB.NET - Use service account to send email impersonating user in G Suite Domain] ' You can install Google.Apis.Auth.OAuth2 by NuGet ' Install-Package Google.Apis.Auth Imports System Imports System.Collections.Generic Imports System.Text Imports System.Threading Imports System.Threading.Tasks Imports System.Security.Cryptography.X509Certificates Imports System.Net Imports System.IO Imports Google.Apis.Auth.OAuth2 Imports EASendMail Public Sub SendMail() Try ' service account email address Const serviceAccount As String = "xxxxxx@xxxxx.iam.gserviceaccount.com" ' import service account key p12 certificate. Dim certificate = New X509Certificate2("D:\MyData\myoauth-77dec4d192ec.p12", "notasecret", X509KeyStorageFlags.Exportable) ' G Suite user email address Dim gsuiteUser = "user@gsuitdomain.com" Dim serviceAccountCredentialInitializer = New ServiceAccountCredential.Initializer(serviceAccount) With { .User = gsuiteUser, .Scopes = {"https://mail.google.com/"} }.FromCertificate(certificate) ' if service account key is in json format, copy the private key from json file: ' "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" ' and import it like this: ' Dim privateKey As String = "-----BEGIN PRIVATE KEY-----" & vbLf & "MIIEv...revdd" & vbLf & "-----END PRIVATE KEY-----" & vbLf ' Dim serviceAccountCredentialInitializer = New ServiceAccountCredential.Initializer(serviceAccount) With { ' .User = gsuiteUser, ' .Scopes = {"https://mail.google.com/"} ' }.FromPrivateKey(privateKey) ' request access token Dim credential = New ServiceAccountCredential(serviceAccountCredentialInitializer) If Not credential.RequestAccessTokenAsync(CancellationToken.None).Result Then Throw New InvalidOperationException("Access token failed.") End If Dim server = New SmtpServer("smtp.gmail.com 587") server.ConnectType = SmtpConnectType.ConnectSSLAuto server.User = gsuiteUser server.Password = credential.Token.AccessToken server.AuthType = SmtpAuthType.XOAUTH2 Dim mail = New SmtpMail("TryIt") mail.From = gsuiteUser mail.[To] = "support@emailarchitect.net" mail.Subject = "service account oauth test" mail.TextBody = "this is a test, don't reply" Dim smtp = New SmtpClient() smtp.SendMail(server, mail) Console.WriteLine("Message delivered!") Catch ep As Exception Console.WriteLine(ep.ToString()) End Try End Sub
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 .
Online Tutorial
C# - Send Email using Google/Gmail
OAuth 2.0
Authentication
C# - Send Email using Gmail/G Suite
OAuth
2.0 in Background Service (Service Account)
C# - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) from Hotmail/Outlook Account
C# - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
C# - Send Email using Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
VB - Send Email using Google/Gmail
OAuth 2.0
Authentication
VB - Send Email using Gmail/G Suite
OAuth
2.0 in Background Service (Service Account)
VB - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) from Hotmail/Outlook Account
VB - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
VB - Send Email using Microsoft
OAuth
2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
C++/CLI - Send Email using
Google/Gmail
OAuth 2.0
Authentication
C++/CLI - Send Email using Gmail/G
Suite OAuth
2.0 in Background Service (Service Account)
C++/CLI - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) from Hotmail/Outlook Account
C++/CLI - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 Account
C++/CLI - Send Email using
Microsoft
OAuth 2.0
(Modern Authentication) + EWS Protocol from Office 365 in Background Service
See Also
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
Using EASendMail SMTP .NET Component
From, ReplyTo, Sender and Return-Path
DomainKeys and DKIM Signature
Send E-mail Directly (Simulating SMTP server)
Work with EASendMail Service (Email Queuing)
Bulk Email Sender Guidelines
Process Bounced Email (Non-Delivery Report) and Email Tracking
EASendMail .NET Namespace References
EASendMail SMTP Component Samples