本文介绍了无法使用Gmail API节点JS发送邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已按照 gmail api 发送电子邮件.我收到以下错误消息:
I have followed gmail api for sending email. I am getting error as:
这是我编写的用于通过带有node.js的gmail api发送邮件的代码段.帮我解决问题.
Here is the piece of code I have written for sending mail using gmail api with node.js. Help me out to resolve the issue.
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("[email protected]", "[email protected]", "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);
})
});
推荐答案
- 您要通过请求模块使用Gmail API发送电子邮件.
- 请使用
https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send
作为端点. - 使用该值作为字符串.
- 在标题中添加
'Content-Type':'message/rfc822'
. - Please use
https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send
as the endpoint. - Use the value as a string.
- Add
'Content-Type': 'message/rfc822'
to the headers.
如果我的理解是正确的,那么该修改如何?我认为有几个答案.因此,请将此视为其中之一.
If my understanding is correct, how about this modification? I think that there are several answers. So please think of this as one of them.
请如下修改 makeBody()
.
function makeBody(to, from, subject, message) {
let str = [
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message,
].join('');
return str;
}
请按以下方式修改选项
.
let raw = makeBody("[email protected]", "[email protected]", "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,
};
注意:
- 此修改后的脚本假定在API控制台上启用了Gmail API,并且访问令牌的范围中包括了发送电子邮件所需的范围.
在我的环境中,我可以确认此修改后的脚本可以正常工作.但是,如果这不是您想要的,对不起.
In my environment, I could confirm that this modified script worked fine. But if this was not what you want, I'm sorry.
这篇关于无法使用Gmail API节点JS发送邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!