I’m trying to build a Node.js app that connects to Gmail API but keep getting errors. Here’s my current setup:
app.get("/emails", function(req, res, next) {
var credentials = require('../service-account.json');
var authClient = new google.auth.JWT(
credentials.client_email,
null,
credentials.private_key,
['https://www.googleapis.com/auth/gmail.readonly'],
null
);
authClient.authorize(function (error, token) {
if (error) {
res.send('Auth failed');
return;
}
console.log('Authentication token: ', token)
gmail.users.labels.list({
auth: authClient,
userId: 'me'
}, function (error, response) {
console.log(error)
res.send('Done')
});
});
});
The error I get is: failedPrecondition: Bad Request. I read somewhere that service accounts only work with paid Google Workspace accounts, not regular Gmail. Is this actually true?
My goal is simple - I have a Gmail account that receives newsletters and I want to create an API endpoint that shows all emails automatically without requiring users to login manually. What’s the best way to accomplish this?
You’re right - service accounts don’t work with personal Gmail. Hit this same wall last year building something similar. Service accounts only work with Google Workspace accounts that have domain-wide delegation set up. For personal Gmail, you need OAuth2 instead. You’ll have to authenticate once to get refresh tokens, but after that your app can auto-refresh access tokens without bugging the user. Just store the refresh token somewhere safe and use it to keep accessing your Gmail data. If you’re just reading emails, IMAP might be easier. Turn on IMAP in Gmail settings and use an app password. Way simpler for reading newsletters.
yeah, that’s a common gmai API issue. service accounts only work with google workspace - personal gmail accounts won’t accept them. for automated access to your own account without manual logins, you’ve gotta use oauth2. run the consent flow once to grab a refresh token, then your app can pull emails automatically. or just skip the hassle and use imap with an app password - way easier for basic email fetching.
Service accounts won’t work with regular Gmail accounts - I learned this the hard way. That failedPrecondition error is what you get when you try using service account credentials on personal Gmail.
Since you’re just pulling from your own account for newsletters, set up OAuth2 with a simple one-time consent flow. Create credentials in Google Cloud Console, run the auth flow once to grab your refresh token, then store it securely. Your app uses the refresh token to get new access tokens automatically - no user interaction needed.
Alternatively, just enable Gmail’s IMAP access and use that instead of the API. Way simpler auth with app passwords, and it works fine for basic email reading.