Using Gmail SMTP OAUTH


The Gmail 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. This way is more secure, but a little bit complex.

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.

Using Gmail API + OAUTH to send email


Use client id and client secret to get access token

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 with Gmail SMTP server

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, C#, C++] To get the full samples of EASendMail, please refer to Samples section.

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

Sub SendMailWithXOAUTH2(userEmail As String, accessToken As String)

    Try
    ' set Gmail SMTP server address
        Dim oServer As SmtpServer = New SmtpServer("smtp.gmail.com")

    ' set SSL connection
        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
    ' set smtp server port, you can also use 465 port
        oServer.Port = 587

    ' use Gmail SMTP 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 OAUTH Authentication] using System; using EASendMail; void SendMailWithXOAUTH2(string userEmail, string accessToken) { try { // Gmail SMTP server address SmtpServer oServer = new SmtpServer("smtp.gmail.com"); // enable SSL connection oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; // Using 587 port, you can also use 465 port oServer.Port = 587; // use Gmail SMTP 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 OAUTH Authentication] using namespace System; using namespace EASendMail; void SendMailWithXOAUTH2(String^ userEmail, String^ accessToken) { try { // Gmail SMTP server address SmtpServer ^oServer = gcnew SmtpServer("smtp.gmail.com"); // set SSL connection oServer->ConnectType = SmtpConnectType::ConnectSSLAuto; // set smtp server port, you can also use 465 oServer->Port = 587; // use Gmail SMTP 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

User Authentication and SSL Connection
Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2
Using Gmail/GSuite Service Account + SMTP OAUTH Authentication
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