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

// 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");


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

Connecting to GMail SMTP/IMAP

Some users fequently ask me how to connect to GMail SMTP service with VMime. You have to connect to server using SMTP protocol (not SMTPS), and set the connection.tls property to true to initiate a secured connection using STARTTLS.

The following code is known to work:

vmime::utility::url url("smtp://smtp.gmail.com");
vmime::ref <vmime::net::transport> tr = session->getTransport(url);
tr->setProperty("connection.tls", true);
tr->setProperty("auth.username", "gmail-login");
tr->setProperty("auth.password", "gmail-password");
tr->setProperty("options.need-authentication", true);

To connect to IMAP on GMail, use the following code:

vmime::utility::url url("imaps://login:password@imap.gmail.com:993");
vmime::ref <vmime::net::store> store = session->getStore(url);