无法通过谷歌API发送邮件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法通过谷歌API发送邮件相关的知识,希望对你有一定的参考价值。

我一直在尝试使用Google的Gmail API发送电子邮件,但我一直收到以下错误消息:

API返回错误:错误:'raw'RFC822有效负载消息字符串或通过/ upload / * URL上传消息


我使用谷歌为NodeJS(documentation)提供的入门代码进行了设置。

const google = require('googleapis');
const googleAuth = require('google-auth-library');
const Base64 = require('js-base64').Base64;

// ...

// create the email string
const emailLines = [];

emailLines.push("From: "My Name" <MY_EMAIL@gmail.com>");
emailLines.push("To: YOUR_EMAIL@uw.edu");
emailLines.push('Content-type: text/html;charset=iso-8859-1');
emailLines.push('MIME-Version: 1.0');
emailLines.push("Subject: New future subject here");
emailLines.push("");
emailLines.push("And the body text goes here");
emailLines.push("<b>And the bold text goes here</b>");
const email =email_lines.join("
").trim(); 

// ...

function sendEmail(auth) {
  const gmail = google.gmail('v1');

  const base64EncodedEmail = Base64.encodeURI(email);
  base64EncodedEmail.replace(/+/g, '-').replace(///g, '_')
  console.log(base64EncodedEmail);

  gmail.users.messages.send({
    auth: auth,
    userId: "me",
    resource: {
      raw: base64EncodedEmail
    }
  }, (err, response) => {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    console.log(response);
  });
}

你可以将auth描述为一个物体:

{
  transporter: ...,
  _certificateCache: ...,
  _certificateExpiry: ...,
  _clientId: ...,
  _clientSecret: ...,
  _redirectUri: ...,
  _opts: {},
  credentials: { 
    access_token: ...,
    refresh_token: ...,
    token_type: 'Bearer',
    expiry_date: 1517563087857 
  } 
}

重要的是access_token


我已经尝试了这里列出的解决方案:

但它们都没有奏效。但是,当我将编码后的字符串复制并粘贴到Google自己的文档的Playground上时,它可以正常工作(documentation):

playground

因此,我改为使用fetch请求,它也有效。

fetch(`https://www.googleapis.com/gmail/v1/users/me/messages/send`, {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + `the_access_token_in_auth_obj`,
    'HTTP-Version': 'HTTP/1.1',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    raw: base64EncodedEmail
  })
})
.then((res) => res.json())
.then((res) => console.info(res));

谁能解释为什么会这样?这是来自googleapi的错误还是我错过了什么?

答案

我遇到了相同的“RFC822有效负载消息字符串或通过/ upload / * URL上传消息”。 quickstart/nodejs示例指定了导致此错误的google-auth-library版本。快速入门指定:

npm install google-auth-library@0.* --save

当我改变这个

npm install google-auth-library -- save

它在版本1.3.1和0.12.0中拉升。一旦我更改代码以解决重大变化,一切都开始工作了。最新版本的googleapis也有重大变化。以下是我对快速入门的调整:

的package.json

 ....
  "dependencies": {
    "google-auth-library": "^1.3.1",
    "googleapis": "^26.0.1"
  }

quickstart.js

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
const {GoogleAuth, JWT, OAuth2Client} = require('google-auth-library');


var SCOPES = [
    'https://mail.google.com/',
    'https://www.googleapis.com/auth/gmail.modify',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.send'
];

var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';

function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];
    var auth = new GoogleAuth();
    var oauth2Client = new OAuth2Client(clientId, clientSecret, redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function (err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
        } else {
            oauth2Client.credentials = JSON.parse(token);
            callback(oauth2Client);
        }
    });
}

function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    console.log('Authorize this app by visiting this url: ', authUrl);
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Enter the code from that page here: ', function (code) {
        rl.close();
        oauth2Client.getToken(code, function (err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
                return;
            }
            oauth2Client.credentials = token;
            storeToken(token);
            callback(oauth2Client);
        });
    });
}


function makeBody(to, from, subject, message) {
    var str = ["Content-Type: text/plain; charset="UTF-8"
",
        "MIME-Version: 1.0
",
        "Content-Transfer-Encoding: 7bit
",
        "to: ", to, "
",
        "from: ", from, "
",
        "subject: ", subject, "

",
        message
    ].join('');

    var encodedMail = new Buffer(str).toString("base64").replace(/+/g, '-').replace(///g, '_');
        return encodedMail;
}

function sendMessage(auth) {
    var gmail = google.gmail('v1');
    var raw = makeBody('xxxxxxxx@hotmail.com', 'xxxxxxx@gmail.com', 'test subject', 'test message');
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {
            raw: raw
        }
    }, function(err, response) {
        console.log(err || response)
    });
}

const secretlocation = 'client_secret.json'

fs.readFile(secretlocation, function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    authorize(JSON.parse(content), sendMessage);
});

现在,当我跑步时,我得到了回应

Object {status: 200, statusText: "OK", headers: Object, config: Object, request: ClientRequest, …}
另一答案

添加到@grabbag's的答案,其中排除了store_token的定义。正如Drive quickstart所说,该功能可以定义如下:

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

以上是关于无法通过谷歌API发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

无法通过 gmail api 向多个发件人发送电子邮件

使用谷歌日历的谷歌数据 API 创建新活动时向客人发送电子邮件

我应该如何使用 Outlook 发送代码片段?

尝试使用 Google.Apis.Gmail 从 asp.net core web api 应用程序从谷歌工作区发送电子邮件时出错

如何通过活页夹将服务发送到 API 级别 14 的片段?

通过 Gmail REST API 发送的电子邮件/草稿无法在新的 Gmail 用户界面中打开