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

时间:2019-05-03 08:08:07

标签: node.js gmail buffer gmail-api rfc2822

我想使用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

edit:显示整个代码。此代码仍然会出现相同的错误。

这几乎是Google的示例,我认为代码中有bug。
我添加了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

1 个答案:

答案 0 :(得分:1)

此修改如何?

发件人:

].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);
    }
  );
}