XOAUTH2 authentication (GMail)

It’s been a while! Today, XOAUTH2 authentication mechanism was implemented into VMime, thanks to Kevin Xi. This SASL authentication mechanism is used by Google GMail.

Here is a brief and simple example of how to use it:


// Indicate that we want to use XOAUTH2 SASL mechanism
vmime::security::sasl::SASLMechanismFactory::getInstance()->
    registerMechanism <vmime::security::sasl::XOAuth2SASLMechanism>("XOAUTH2");

// Create a new session
vmime::shared_ptr <vmime::net::session> sess = vmime::net::session::create();

// Use a custom authenticator to force using XOAUTH2 mechanism
vmime::shared_ptr <vmime::security::authenticator> xoauth2Auth =
    vmime::make_shared <vmime::security::sasl::XOAuth2SASLAuthenticator>
        (vmime::security::sasl::XOAuth2SASLAuthenticator::MODE_EXCLUSIVE);

// Create a new SMTPS service to GMail
vmime::shared_ptr <vmime::net::transport> tr = sess->getTransport(
    vmime::utility::url("smtps://smtp.gmail.com:465"), xoauth2Auth
);

tr->setProperty("options.need-authentication", true);
tr->setProperty("auth.username", "your-email@gmail.com");
tr->setProperty("auth.accesstoken", "ya29.5MEMlacTJifpYHHGn3V...your-access-token...kIOWy3wft5Rs");

tr->connect();

// Do whatever you want with 'tr' here!

In the previous example, if the XOAUTH2 authentication fails, no other authentication mechanism will be tried. If you want to fall back on basic username/password authentication mechanism if XOAUTH2 fails, simply replace MODE_EXCLUSIVE with MODE_SUGGEST. And don’t forget to also set the auth.password property!

For more information about XOAUTH2, see OAuth 2.0 mechanism on Google Developers page.

Comments are closed.