我收到 Gmail 所需的收件人地址错误 API

I got error Recipient address required with Gmail API

我想用 Gmail API 发送电子邮件。

文档说 Gmail API 需要 RFC2822 格式和 base64 编码的字符串。
所以我写电子邮件内容并将其传递给原始 属性.
但是我得到了错误:Recipient address required.

我该如何解决这个问题?

这是我的代码。

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

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Gmail API.
  authorize(JSON.parse(content), sendGmail);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

function sendGmail(auth){
  const makeBody = (params) => {
      params.subject = new Buffer.from(params.subject).toString("base64");
      const str = [
          'Content-Type: text/plain; charset=\"UTF-8\"\n',
          'MINE-Version: 1.0\n',
          'Content-Transfer-Encoding: 7bit\n',
          `to: ${params.to} \n`,
          `from: ${params.from} \n`,
          `subject: =?UTF-8?B?${params.subject}?= \n\n`,
          params.message
      ].join(' ');
      return new Buffer.from(str).toString('base64').replace(/\+/g,'-').replace(/\//g,'_');
  }

  const messageBody = `
  this is a test message
  `;

  const raw = makeBody({
      to : 'foo@gmail.com',
      from : 'foo@gmail.com',
      subject : 'test title',
      message:messageBody
  });
jj

  const gmail = google.gmail({version:'v1',auth:auth});
  gmail.users.messages.send({
      userId:"me",
      resource:{
          raw:raw
      }
  }).then(res => {
    console.log(res);
  });
}

结果:

Error: Recipient address required

编辑:显示完整代码。此代码仍然出现相同的错误。

这几乎是 Google 的示例,我认为我的代码中存在错误。
我添加 sendGnail 方法并将 authorize(JSON.parse(content), listLabels); 编辑为 authorize(JSON.parse(content), sendGmail); ,更改 SCOPES 并删除 listLabels 方法。
(listLabels 方法工作正常。)
执行 listLabels 方法后,我更改 SCOPES 并重新创建 token.json.
获取标签后,我更改

这是示例 https://developers.google.com/gmail/api/quickstart/nodejs?hl=ja

这个修改怎么样?

发件人:

].join(' ');

收件人:

].join('');

注:

  • 我认为脚本可以通过上述修改工作。但是作为一个修改点,从 'Content-Type: text/plain; charaset=\"UTF-8\"\n', 修改为 'Content-Type: text/plain; charset=\"UTF-8\"\n', 怎么样?

如果这不是直接的解决方案,我深表歉意。

编辑:

我在你的脚本中修改了 sendGmail 的功能。

修改后的脚本:

function sendGmail(auth) {
  const makeBody = params => {
    params.subject = new Buffer.from(params.subject).toString("base64");
    const str = [
      'Content-Type: text/plain; charset="UTF-8"\n',
      "MINE-Version: 1.0\n",
      "Content-Transfer-Encoding: 7bit\n",
      `to: ${params.to} \n`,
      `from: ${params.from} \n`,
      `subject: =?UTF-8?B?${params.subject}?= \n\n`,
      params.message
    ].join(""); // <--- Modified
    return new Buffer.from(str)
      .toString("base64")
      .replace(/\+/g, "-")
      .replace(/\//g, "_");
  };

  const messageBody = `
  this is a test message
  `;

  const raw = makeBody({
    to: "foo@gmail.com",
    from: "foo@gmail.com",
    subject: "test title",
    message: messageBody
  });

  const gmail = google.gmail({ version: "v1", auth: auth });
  gmail.users.messages.send(
    {
      userId: "me",
      resource: {
        raw: raw
      }
    },
    (err, res) => { // Modified
      if (err) {
        console.log(err);
        return;
      }
      console.log(res.data);
    }
  );
}