【问题标题】:Send email from G-Suite in nodejs server using Gmail API returns 400 bad request使用 Gmail API 从 nodejs 服务器中的 G-Suite 发送电子邮件返回 400 错误请求
【发布时间】:2020-10-25 22:37:38
【问题描述】:

我想使用 Gmail API 从我在 nodejs 服务器中的 G-Suite 帐户发送一封电子邮件。 我知道凭据没问题,因为我从 G-Suite 获取消息/标签没有问题。

这是我的代码:

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;
  }
}

我将 sendcomposemodify 的范围添加到 Admin Google,不幸的是我收到了这个 400 错误请求:

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

【问题讨论】:

    标签: node.js google-api gmail-api google-api-nodejs-client google-auth-library


    【解决方案1】:

    使用 googleapis 库。

    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,
        },
      });
    }

    【讨论】:

    • 酷!你的回答解决了我的问题。谢谢百万。
    猜你喜欢
    • 2019-06-27
    • 2018-03-15
    • 2017-08-11
    • 2020-05-27
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多