我已按照gmail api发送电子邮件。我收到以下错误消息:
“邮件”:“ 400-\” {\ n \\“错误\\”:{\ n \\“错误\\”:[\ n {\ n \\“域\\”:\\ “ global \\”,\ n \\“原因\\”:\\“ invalidArgument \\”,\ n \\“消息\\”:\\“原始RFC822有效负载消息字符串或通过/ upload上传消息/ *必需的网址\\“ \ n} \ n],\ n \\”代码\\“:400,\ n \\”消息\\“:\\”原始RFC822有效负载消息字符串或通过上载消息/ upload / *必须输入网址\\“ \ n} \ n} \ n \”“
这是我编写的用于使用带有node.js的gmail api发送邮件的代码。帮我解决问题。
router.post('/composeMail', async (req, res, next) => {
function makeBody(to, from, subject, message) {
let str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"Content-length: 5000\n",
"Content-Transfer-Encoding: message/rfc822\n",
"to: ", to,"\n",
"from: ", from,"\n",
"subject: ", subject,"\n\n",
message
].join('');
console.log("String: ", str);
// let encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
let encodedMail = btoa(str).replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
let raw = makeBody("dinesh.kumar@gmail.com", "dinesh.kumar@gmail.com", "Test mail", "Everything is fine");
let obj = {};
obj.raw = raw;
let body = JSON.stringify(obj);
let option = {
url: "https://www.googleapis.com/gmail/v1/users/userId/messages/send",
method: 'POST',
headers: {
'Authorization': `Bearer ${req.query.access_token}`
},
qs: {
userId: 'me'
},
body: body
};
await request(option).then(body => {
return res.apiOk(body);
}).catch(err => {
return res.apiError(err);
})
});
答案 0 :(得分:1)
如果我的理解是正确的,那么该修改如何?我认为有几个答案。因此,请将此视为其中之一。
https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send
作为端点。'Content-Type': 'message/rfc822'
。请如下修改makeBody()
。
function makeBody(to, from, subject, message) {
let str = [
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message,
].join('');
return str;
}
请如下修改option
。
let raw = makeBody("dinesh.kumar@gmail.com", "dinesh.kumar@gmail.com", "Test mail", "Everything is fine");
const userId = 'me'; // Please modify this for your situation.
let option = {
url: "https://www.googleapis.com/upload/gmail/v1/users/" + userId + "/messages/send",
method: 'POST',
headers: {
'Authorization': `Bearer ${req.query.access_token}`,
'Content-Type': 'message/rfc822',
},
body: raw,
};
在我的环境中,我可以确认此修改后的脚本可以正常工作。但是,如果这不是您想要的,对不起。