我的nodejs程序无法使用Gmail api发送消息。
解决方案来自用于在 Node.js 中发送邮件的 Gmail API https://stackoverflow.com/questions/34546142/gmail-api-for-sending-mails-in-node-js对我不起作用。
我用以下方式对电子邮件进行编码
var {google} = require('googleapis');
// to and from = "some name <blaw.blaw.com"
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\r\n",
"MIME-Version: 1.0\r\n",
"Content-Transfer-Encoding: 7bit\r\n",
"to: ", to, "\r\n",
"from: ", from, "\r\n",
"subject: ", subject, "\r\n\r\n",
message
].join('');
encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
然后转到 Google API 浏览器https://developers.google.com/apis-explorer/#p/ https://developers.google.com/apis-explorer/#p/输入 gmail.users.messages.send 和上面 make_body 生成的字符串。
电子邮件将成功发送。所以我知道上面的编码是
好的。
当我的程序尝试使用以下命令发送时,它失败并出现错误
错误:“原始”RFC822 有效负载消息字符串或通过上传消息
/上传/* 需要 URL
function sendMessage(auth) {
var gmail = google.gmail('v1');
var raw = makeBody('john g <[email protected] /cdn-cgi/l/email-protection>', 'john g<[email protected] /cdn-cgi/l/email-protection>', 'test subject', 'test message #2');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
}
身份验证令牌很好,因为我可以调用 gmail.users.labels.list,并且在使用 API 资源管理器时使用相同的授权。
Q1:有谁知道为什么上面不起作用?
Q2: 用于在 Node.js 中发送邮件的 Gmail API https://stackoverflow.com/questions/34546142/gmail-api-for-sending-mails-in-node-js没有解释为什么原始电子邮件被包装在资源字段中。我尝试简单地生吃,但没有帮助。
这失败了。
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
也是如此
gmail.users.messages.send({
auth: auth,
userId: 'me',
raw: raw
}, function(err, response) {
console.log(err || response)
});
这也是如此用于发送带有附件的电子邮件的 GMAIL API https://stackoverflow.com/questions/31784167/gmail-api-for-sending-email-with-attachment
gmail.users.messages.send({
auth: auth,
userId: 'me',
data: raw
}, function(err, response) {
console.log(err || response)
});
有谁知道它在哪里记录了如何传递 api 资源管理器所要求的“请求正文”?
Q3:为什么google api需要base64编码的替换?
我尝试使用编码
const Base64 = require("js-base64").Base64
var encodedMail = Base64.encode(str);
当我将其输入 API 资源管理器时,出现错误
"message": "字节字符串的值无效: