Send mail via Google Apps Gmail using service account domain wide delegation in nodejs
So I was half-step close to the solution, the problem was that while creating const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], null);
i did not mention the account to be impersonated.
The correct initialization should be:
const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], '[email protected]');
To summarize, the correct steps are:
- Created a project in Google Cloud Platform
- Created a service account
- Enabled
Domain Wide Delegation
for the service account - Downloaded the key for the service account in JSON format
-
API Manager
>Credentials
i have createdOAuth 2.0 Client ID
- Enabled Gmail API for the project
In Google Apps Admin console:
- In
Security
>Advanced Settings
>Manage API client access
i have added theClient ID
from step 4 above - I have added all possible scopes for the
Client ID
This is the code that sends mails:
const google = require('googleapis');
const googleKey = require('./google-services.json');
const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], '<user to impersonate>');
jwtClient.authorize((err, tokens) => {
if (err) {
console.err(err);
return;
}
console.log('Google auth success')
var gmail = google.gmail({version: 'v1'})
var raw = <build base64 string according to RFC 2822 specification>
var sendMessage = gmail.users.messages.send({
auth: jwtClient,
userId: '<user to impersonate>',
resource: {
raw: raw
}
}, (err, res) => {
if (err) {
console.error(err);
} else {
console.log(res);
}
});
Hope that would be helpful for others