【问题标题】:I got error Recipient address required with Gmail API我收到错误 Gmail API 需要收件人地址
【发布时间】:2019-09-21 18:09:36
【问题描述】:

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

【问题讨论】:

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


    【解决方案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);
        }
      );
    }
    

    【讨论】:

    • no.. 它不起作用... 我这样称呼这个函数js // Load client secrets from a local file. fs.readFile('credentials.json', (err, content) =&gt; { 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); }); 这是错的吗?
    • @invalid 感谢您的回复。我带来的不便表示歉意。在我的环境中,我已经通过上述修改确认您的脚本可以正常工作。所以我认为你的下一个问题与你的问题的脚本不同。从it does not work. 和您评论中的脚本,我无法理解您的情况。那么你能提供整个脚本吗?当然,请删除您的个人信息。如果可以,请将其添加到您的问题中。借此,我想确认您的下一个问题。如果您能合作解决您的问题,我很高兴。
    • @invalid 感谢您更新您的问题。从您的脚本中,我修改了您脚本中sendGmail 的功能。你能确认一下吗?
    • @invalid 很高兴您的问题得到解决。也谢谢你。
    猜你喜欢
    • 2020-08-23
    • 2018-08-14
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2021-10-23
    • 2015-07-22
    • 2017-04-30
    相关资源
    最近更新 更多