Using Gmail RESTFul API + OAUTH


Gmail supports SMTP + OAUTH, but the API (https://mail.google.com/) scope is restricted API which requests to have full access to the Gmail account. Restricted API is throttled before your project is authenticated in by Google.

Using less restricted API (https://www.googleapis.com/auth/gmail.send) scope to send email via Gmail server is recommended.

https://developers.google.com/gmail/oauth_overview?hl=en

Create your project in Google Developers Console

To use Gmail OAUTH in your application, you must create a project in Google Developers Console at first.

Scope Remarks

Gmail supports SMTP + OAUTH, but the API (https://mail.google.com/) scope is restricted API which requests to have full access to the Gmail account. Restricted API is throttled before your project is authenticated in by Google.

Using less restricted API (https://www.googleapis.com/auth/gmail.send) scope to send email via Gmail server is recommended.


You can use client id and client secret to get the user email address and access token like this:

You should create your client id and client secret, don't use the client id in the sample project, it is only for test purpose. If you got "This app isn't verified" information, please click "advanced" -> Go to ... for test.

Example

[C# - Get access token and user with Google.Apis.Auth.OAuth2]
// You can install Google.Apis.Auth.OAuth2 by NuGet
// Install-Package Google.Apis.Auth

using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "put your client id here",
            ClientSecret = "put your client secret here"
        },
        new[] { "email", "profile", "https://mail.google.com/" },
        "user",
        CancellationToken.None
        );

var jwtPayload = GoogleJsonWebSignature.ValidateAsync(credential.Token.IdToken).Result;
var username = jwtPayload.Email;

// then you can get access token and user from the following properties
// credential.Token.AccessToken;
// username;


Use access token to send email via Gmail RESTFul API

After you get user email address and access token, you can use the following codes to send email using Gmail SASL XOAUTH2 mechanism.

Example

[Visual Basic 6.0, VC++, Delphi] To get the full samples of EASendMail, please refer to Samples section.

[VB - Send Email using Gmail API + OAUTH Authentication]
    
Imports EASendMail

Sub SendMailWithXOAUTH2(userEmail As String, accessToken As String)

    Try
    ' set Gmail API address
        Dim oServer As SmtpServer = New SmtpServer("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media")

    ' set Gmail RESTFul API protocol 
        oServer.Protocol = ServerProtocol.GmailApi

    ' set SSL connection
        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
        
    ' use Gmail OAUTH 2.0 authentication
        oServer.AuthType = SmtpAuthType.XOAUTH2
    ' set user authentication
        oServer.User = userEmail
    ' use access token as password
        oServer.Password = accessToken

        Dim oMail As SmtpMail = New SmtpMail("TryIt")
        oMail.From = New MailAddress(userEmail)
        oMail.To.Add(New MailAddress("support@emailarchitect.net"))

        oMail.Subject = "test email sent from VB using Gmail OAUTH"
        oMail.TextBody = "test body"

        Dim oSmtp As SmtpClient = New SmtpClient
        oSmtp.SendMail(oServer, oMail)

        Console.WriteLine("The email has been submitted to server successfully!")

    Catch exp As Exception
        Console.WriteLine("Exception: {0}", exp.Message)
    End Try

End Sub
    

[C# - Send Email using Gmail API + OAUTH Authentication] using System; using EASendMail; void SendMailWithXOAUTH2(string userEmail, string accessToken) { try { // Gmail API server address SmtpServer oServer = new SmtpServer("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media"); // set Gmail RESTFul API protocol oServer.Protocol = ServerProtocol.GmailApi; // enable SSL connection oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; // use Gmail OAUTH 2.0 authentication oServer.AuthType = SmtpAuthType.XOAUTH2; // set user authentication oServer.User = userEmail; // use access token as password oServer.Password = accessToken; SmtpMail oMail = new SmtpMail("TryIt"); // Your gmail email address oMail.From = userEmail; oMail.To = "support@emailarchitect.net"; oMail.Subject = "test email from gmail account with OAUTH 2"; oMail.TextBody = "this is a test email sent from c# project with gmail."; Console.WriteLine("start to send email using OAUTH 2.0 ..."); SmtpClient oSmtp = new SmtpClient(); oSmtp.SendMail(oServer, oMail); Console.WriteLine("The email has been submitted to server successfully!"); } catch (Exception ep) { Console.WriteLine("Exception: {0}", ep.Message); } }
[C++/CLI - using Gmail API + OAUTH Authentication] using namespace System; using namespace EASendMail; void SendMailWithXOAUTH2(String^ userEmail, String^ accessToken) { try { // Gmail API server address SmtpServer ^oServer = gcnew SmtpServer("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media"); // set Gmail RESTFul API protocol oServer->Protocol = ServerProtocol::GmailApi; // set SSL connection oServer->ConnectType = SmtpConnectType::ConnectSSLAuto; // use Gmail OAUTH 2.0 authentication oServer->AuthType = SmtpAuthType::XOAUTH2; //set user authentication oServer->User = userEmail; // use access token as password oServer->Password = accessToken; SmtpMail ^oMail = gcnew SmtpMail("TryIt"); oMail->From = gcnew MailAddress(userEmail); oMail->To->Add(gcnew MailAddress("support@emailarchitect.net")); oMail->Subject = "test email sent from C++/CLI using Gmail OAUTH"; oMail->TextBody = "test body"; SmtpClient ^oSmtp = gcnew SmtpClient(); oSmtp->SendMail(oServer, oMail); Console::WriteLine("The email has been submitted to server successfully!"); } catch (System::Exception ^exp) { Console::WriteLine("Exception: {0}", exp->Message); } }

Remarks

If your application is background service which doesn't support user interaction, please have a look at this topic: Use G Suite service account to do SMTP OAUTH.

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

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 Gmail/GSuite Service Account + SMTP OAUTH Authentication
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