node.js - 我收到错误 Gmail API 需要收件人地址

标签 node.js gmail buffer gmail-api rfc2822

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

文档称 Gmail API 需要 RFC2822 格式和 base64 编码的字符串。
因此,我编写电子邮件内容并将其传递给原始属性。
但我收到错误:需要收件人地址。

我该如何解决这个问题?

这是我的代码。

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 : '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6701080827000a060e0b4904080a" rel="noreferrer noopener nofollow">[email protected]</a>',
      from : '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5851517e59535f5752105d5153" rel="noreferrer noopener nofollow">[email protected]</a>',
      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;字符集=\"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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8b8282ad8a808c8481c38e8280" rel="noreferrer noopener nofollow">[email protected]</a>",
    from: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72141d1d32151f131b1e5c111d1f" rel="noreferrer noopener nofollow">[email protected]</a>",
    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);
    }
  );
}

关于node.js - 我收到错误 Gmail API 需要收件人地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55965680/

相关文章:

javascript - Node Sequelize 回调 promise 期望一个函数,是否有通过函数调用删除声明函数的方法

javascript - node.js/JavaScript 语法 - 向传递的参数添加额外的参数

c# - 为什么 GMail 无法识别代码发送的 session 请求?

C++ 刷新缓冲区

node.js - 使用 NodeJS 的 QnAMaker 自适应卡

node.js - 从 firebase 函数连接到 MongoDB Atlas

c# - 如何使用 MailKit 发送电子邮件?

c# - 从 C# 读取 gmail 帐户的 Atom 提要

c - 将图像保存到缓冲区

emacs - 使用 emacs 启动缓冲区,其行为类似于 Scratch