Send mail using Gmail API with service account

Viewed 778

this is my barebones code. I want to send an email as one of the users of my domain. The email might be different every call.

const { google } = require('googleapis');

function makeBody(to, from, subject, message) {
    const str = [
        'Content-Type: text/plain; charset="UTF-8"\n',
        'MIME-Version: 1.0\n',
        'Content-Transfer-Encoding: 7bit\n',
        'to: ', to, '\n',
        'from: ', from, '\n',
        'subject: ', subject, '\n\n',
        message,
    ].join('');

    return Buffer.from(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
}

class MailProvider {
    gmail = google.gmail({
        version: 'v1',
        auth: new google.auth.GoogleAuth({
            keyFile: '../../assets/secrets/google.json', // See below
            scopes: [
                'https://mail.google.com/',
                'https://www.googleapis.com/auth/gmail.addons.current.action.compose',
                'https://www.googleapis.com/auth/gmail.compose',
                'https://www.googleapis.com/auth/gmail.modify',
                'https://www.googleapis.com/auth/gmail.send',
            ],
        }),
    });

    async sendMail(sendAs, sendTo) {
        return this.gmail.users.messages.send({
            userId: sendAs,
            requestBody: {
                raw: makeBody(sendTo, sendAs, 'Test subject', 'Test body'),
            },
        }).catch(console.error);
    }
}

new MailProvider().sendMail('noreply@mydomain.cz', 'akxe@seznam.cz');

Censored google.json:

{
  "type": "service_account",
  "project_id": "firm-aria-ID",
  "private_key_id": "ID",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...key...\n-----END PRIVATE KEY-----\n",
  "client_email": "rita-sm@firm-aria-ID.iam.gserviceaccount.com",
  "client_id": "ID",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/rita-sm%40firm-aria-ID.iam.gserviceaccount.com"
}

I am getting the failedPrecondition error. I don't know what to do anymore... I am at this for more than one full day...

The error:

{
  // ...
  code: 400,
  errors: [
    {
      message: 'Precondition check failed.',
      domain: 'global',
      reason: 'failedPrecondition'
    }
  ]
}
1 Answers

You cannot use a service account for sending emails. You need to use 3 legged oauth and send emails on behalf of the enduser.

Related