Using Gmail/GSuite SMTP OAUTH with Service Account


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" .


Google Service Account

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.


Create your project in Google Developers Console

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.


Create service account under current project

After service account is created, you should enable "Domain-wide delegation" and create service key pair to access G Suite user mailbox.


Enable "Domain-wide delegation" and create service key


Enable Gmail API

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.


Authorize service account by G Suite administrator

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.

After G Suite administrator authorized service account, you can use it to access any users mailbox in G Suite domain.


Use service account to send email impersonating user 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