gpt4 book ai didi

node.js - 通过google api发送邮件失败

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:05 24 4
gpt4 key购买 nike

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

The API returned an error: Error: 'raw' RFC822 payload message string or uploading message via /upload/* URL required

<小时/>

我使用 Google 为 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("\r\n").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\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
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, …}

关于node.js - 通过google api发送邮件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48579566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com