Please guide how to send email using gmail api via gsuit service account
See original GitHub issueMy goal is for my nodejs app to send mail to notify me if there were unhandled code exception on the server.
The code below is what I use for testing, which I modified gmail api quickstart code to use keyFile instead of oauth. However, I stuck with the error “The API returned an error: Error: Invalid Credentials”.
I use this auth code with spreadsheet api before and it was success. I also did enable Domain-wide Delegation and add the app to Google Admin access control with Trusted permission level.
Now I’m stuck and cannot find any nodejs example for gmail. Please help.
import googleapis from 'googleapis'
const {google} = googleapis
const auth = new google.auth.GoogleAuth({
keyFile: './credentials/gmail-key.json',
scopes: ['https://www.googleapis.com/auth/gmail.send,email,profile']
})
const gmail = google.gmail({version: 'v1', auth})
// console.log(gmail.users.messages.send)
listLabels(auth)
function listLabels(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.labels.list({
// I use service account email
userId: 'SERVICE_ACCOUNT_NAME@APP_NAME.iam.gserviceaccount.com',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const labels = res.data.labels;
if (labels.length) {
console.log('Labels:');
labels.forEach((label) => {
console.log(`- ${label.name}`);
});
} else {
console.log('No labels found.');
}
});
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (2 by maintainers)
Top Results From Across the Web
Sending Email | Gmail - Google Developers
There are two ways to send email using the Gmail API: You can send it directly using the messages.send method. You can send...
Read more >GMail API - Can I send email using the Service Account?
The Gmail API is for Gmail users and service accounts are just for doing ... If you want to send the email from...
Read more >Sending emails programmatically with Gmail API and Python
Authorize the service account to send emails · Go to your G Suite domain's Admin console. · Select Security from the list of...
Read more >How to Send Email in WordPress using the Gmail SMTP Server
Step by step guide on how to use the Gmail SMTP servers to send emails in WordPress. Gmail SMTP plugin helps fix the...
Read more >How to Send and Read Emails with Gmail API | Mailtrap Blog
Step 1: Create a project at Google API Console · Step 2: Enable Gmail API · Step 3: Credentials and authentication with OAuth...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I found a way to make this work in a relatively painless way so I’ll share in case someone needs it later. As you know, the docs are kind of useless for us nodejs folks so I’ll put some explaining here too.
First of all, create the service account via Cloud Console or other methods & give it domain-wide delegation. No need to give any other roles or permissions as the GMail API is not exactly a GCloud app. Then head over to the Google Workspaces Admin website (https://admin.google.com) and under security -> API setting (or something similarly named) put the delegation ClientId into the allowed apps list. This is where you set the appropriate scopes too.
Now consider the following (tl;dr at bottom):
tl;dr:
I haven’t used attachments yet. If or when I do, I’ll probably update this.
There’s not, but something our tech writers are looking at improving.
Most Workspace APIs expect to be called as an end-user, not a service account. Support for services accounts is the exception, not the rule, and there’s only a handful of APIs where it’s appropriate (e.g. Drive, though still discouraged.) Gmail and Calendar specifically do not allow it.
They all support domain-wide delegation where a service account is used to impersonate an end-user. But that’s not what this code example is doing. It’s using the service account identity itself which isn’t allowed here. To do delegation, the credentials need to be scoped to the target user by setting the sub claim in the token. Looks like for this client that means creating the JWT client directly (https://github.com/googleapis/google-auth-library-nodejs/blob/master/src/auth/jwtclient.ts) and setting the subject arg to the user’s email address. Some of the other libraries have convenience methods for doing this (similar to createScoped(scopes) – createDelegated(user)) and that could be useful to add here.
The other change would be using the user email (or the ‘me’ alias which just means whoever the effective user is) for the userId parameter in the API request.
To summarize: