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.

Using Client ID and Client secret to get access token

Now you can use client id and client secret to get the user email address and access token. Basically, OAUTH uses HTTP protocol, first of all, user inputs user and password in Google Web Authentication, Google returns access token back to your application, finally your application uses access token to access Gmail SMTP server. You can find the example codes in EASendMail Installation Path\Samples_{Programming language/Developer Tool}\GmailOauth.* project.

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

How to use access token with Gmail SMTP Service.

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

[VB - Send Email using Gmail OAUTH Authentication - XAML]
    
Imports EASendMail
Private Async Function SendEmail(  email As String, access_token as String ) As Task
    Dim oMail As SmtpMail = New SmtpMail("TryIt")
    Dim oSmtp As SmtpClient = New SmtpClient

    Try
        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 = email 

	'use the access token as password
        oServer.Password = access_token 
        
        oMail.From = New MailAddress(email)
        oMail.To.Add(New MailAddress("support@emailarchitect.net"))
        
        oMail.Subject = "test email sent from VB using Gmail OAUTH"
        oMail.TextBody = "test body"
                       
        Await oSmtp.SendMailAsync(oServer, oMail)
        Result = "Email was sent successfully!"

    Catch ep As Exception
        Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
    End Try

    ' Display Result by Diaglog box
    Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
    Await dlg.ShowAsync()

End Sub
    
[C# - Send Email using Gmail OAUTH Authentication - XAML]
using EASendMail;
using System.Threading.Tasks;

private async Task SendEmail(string email, string access_token)
{
    String Result = "";
    try
    {
        SmtpMail oMail = new SmtpMail("TryIt"); 
        SmtpClient oSmtp = new SmtpClient(); 

        // Set sender email address
        oMail.From = new MailAddress( email );

        // Add recipient email address, please change it to yours
        oMail.To.Add(new MailAddress("support@emailarchitect.net"));

        // Set email subject
        oMail.Subject = "test email from gmail account with OAUTH 2"; 

        // Set email body
        oMail.TextBody = "this is a test email sent from c# project with gmail."; 

        // Gmail SMTP server address
        SmtpServer oServer = new SmtpServer("smtp.gmail.com"); 

        // Using 587 port, you can also use 465 port
        oServer.Port = 587;

        // enable SSL connection
        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; 

        // use Gmail SMTP OAUTH 2.0 authentication
        oServer.AuthType = SmtpAuthType.XOAUTH2;
        oServer.User = email; 

        // use the access token as password
        oServer.Password = access_token;   

        await oSmtp.SendMailAsync(oServer, oMail);
        Result = "Email was sent successfully!";
    }
    catch (Exception ep)
    {
        Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
    }

    // Display Result by Diaglog box
    Windows.UI.Popups.MessageDialog dlg = new
        Windows.UI.Popups.MessageDialog(Result);
           
    await dlg.ShowAsync();
} 

[JavaScript - using Gmail OAUTH Authenticationi in Windows Store Apps - HTML5]
function sendMail( email, access_token ) {
    var result = "";

    var oMail = new EASendMail.SmtpMail("TryIt");
    var oSmtp = new EASendMail.SmtpClient();

    // Set sender email address, please change it to yours 
    oMail.from = new EASendMail.MailAddress(email);

    // Add recipient email address, please change it to yours
    oMail.to.add(new EASendMail.MailAddress("support@emailarchitect.net"));

    // Set email subject
    oMail.subject = "test email from JavaScript HTML5 project";

    // Set email body
    oMail.textBody = "this is a test email sent from Windows Store App, do not reply";

    // Your SMTP server address
    var oServer = new EASendMail.SmtpServer("smtp.gmail.com");

    // use Gmail SMTP OAUTH 2.0 authentication
    oServer.authType = EASendMail.SmtpAuthType.xOAUTH2;

    // User and password for Gmail OAUTH authentication            
    oServer.user = email;
    oServer.password = "testpassword";

   
    // Set server port, you can also use 465
    oServer.port = 587;
    oServer.connectType = EASendMail.SmtpConnectType.connectSSLAuto;

    oSmtp.sendMailAsync(oServer, oMail).then(function (e) {
        result = "Email was sent successfully!";

        // Display Result by Diaglog box
        (new Windows.UI.Popups.MessageDialog(result, "Success")).showAsync();
    },

    function (e) {
        // because javascript exception only gives the stack trace messages, but it is not
        // real description of exception, so we give a property lastErrorMessage for javascript.
        if (oSmtp.lastErrorMessage != "") {
            result = oSmtp.lastErrorMessage;
        }
        else {
            result = e.message;
        }
        oSmtp.close();

        // Display Result by Diaglog box
        (new Windows.UI.Popups.MessageDialog(result, "Error Information")).showAsync();
    });
}
    

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.

See Also

User Authentication and SSL Connection
From, ReplyTo, Sender and Return-Path
EASendMail Windows 8 Runtime Component References
EASendMail SMTP Component Samples

Online Tutorials

Send Email in VB - Windows Store App
Send Email in C# - Windows Store App
Send Email in JavaScript - Windows Store App
Send Email in VB 6.0 - Tutorial
Send Email in C# - Tutorial
Send Email in VB.NET - Tutorial
Send Email in Visual C++ - Tutorial
Send Email in Managed C++/CLI - Tutorial
Send Email in Delphi - Tutorial
Send Email in MS SQL stored procedure - Tutorial