Search code examples
node.jsgoogle-apigoogle-oauthgmail-apigoogle-api-nodejs-client

Send email from G-Suite in nodejs server using Gmail API returns 400 bad request


I want to send an email from my G-Suite account in a nodejs server using Gmail API. I know the credentials are ok, cause I have no problem to get messages/labels from my G-Suite.

this is my code:

const {GoogleAuth} = require('google-auth-library');

async sendMessage(to, from, subject, message) {
   let raw = makeBody(to, from, subject, message);
   let url = `https://www.googleapis.com/gmail/v1/users/${<MyEmail>}/messages/send`

   let option = {
       method: 'POST',
       headers: {
           'Content-Type': 'message/rfc822',
       },
       body: raw,
   };

  let client = await getClient()
  client.request({url, option}, (res, err) => {
    if (err) {
        console.log('error', err);
    } else {
        console.log('res');
    }
  });
}

async getClient() {
  try {
    let auth = new GoogleAuth({
        credentials: {
            client_email: <clientEmail>,
            private_key: <privateKey>,
        },
        scopes: [
            "https://mail.google.com/",
            "https://www.googleapis.com/auth/gmail.compose",
            "https://www.googleapis.com/auth/gmail.modify",
            "https://www.googleapis.com/auth/gmail.send"],
        clientOptions: {subject: <myEmail>}
    });
    const client = await auth.getClient();
    if (client)
        return client
  } catch (e) {
     console.log('error accured while getClient', e);
     return e;
  }
}

I added the scopes of send, compose and modify to Admin Google, unfortunately I get this 400 bad request:

 error [
    {
       domain: 'global',
       reason: 'invalidArgument',
       message: 'Invalid id value'
    }
 ]

Solution

  • Use googleapis library.

    const {google} = require('googleapis');
    const gmail = google.gmail('v1');
    
    async sendMessage(to, from, subject, message) {
      let raw = makeBody(to, from, subject, message);
    
      let client = await auth.getClient()
      google.options({
        auth: client
      });
    
      const res = await gmail.users.messages.send({
        userId: 'me',
        requestBody: {
          raw: raw,
        },
      });
    }