javascript - 使用 Gmail API 在 Chrome 应用中发送邮件
问题描述
我正在尝试创建一个 Chrome 应用程序并且我想发送电子邮件。我找到了这个,但我无法弄清楚它是如何工作的。
function sendMessage(userId, to, subject, email) {
authUser(function() {
var base64EncodedEmail = btoa(email);
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'message': {
'raw': base64EncodedEmail,
'headers': [
{'To': to},
{'Subject': subject}
]
}
});
request.execute();
});
}
function authUser(callback) {
chrome.identity.getAuthToken({'interactive': true}, function(token) {
// load Google's javascript client libraries
var url = "https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=" + token;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState !== 4 || request.status !== 200) {
return;
}
var response = JSON.parse(request.responseText);
console.log(response);
callback();
}
;
request.open('POST', url, true);
request.send();
request.setRequestHeader('Authorization', 'Bearer ' + token);
});
}
我将代码放在我的background.js中(在启动时调用 sendMessage),并获得以下manifest.json:
{
"name": "Name",
"description": "Description",
"permissions": [
"storage",
{ "fileSystem": ["write"] },
"identity",
"https://mail.google.com/"],
"version": "1.0",
"manifest_version": 2,
"oauth2": {
"client_id": "XXXXX.apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/gmail.send"
]
},
"app": {
"background": {
"scripts": [
"background.js"]
}
},
"icons": { "16": "images/mailling-16.png", "128": "images/mailling-128.png" }
}
所以,我知道我们需要与Gmail API建立连接(使用我们的凭据),然后我们发送邮件。但我在POST请求和服务器抛出HTTP 错误 400 : 'raw' RFC822 有效负载消息字符串或通过 /upload/* URL 上传消息
我不明白他为什么期待消息,而我们正在建立连接:I
解决方案
我最好的解决方案是切换到谷歌脚本应用程序,您只能使用MailApp.sendEmail发送邮件。
无论如何,这不是 Chrome 应用程序的解决方案。
推荐阅读
- c++ - 使用 unique_ptr 值从 unordered_map 移动的最佳方法
- logback - Playspec 没有选择记录器配置
- python - 如何将索引转换为日期时间
- spring-integration - 路由到错误频道但得到“调度程序没有频道订阅者”
- laravel - 如何在 Laravel 中将 json feed 保存到 MongoDB 并获取密钥?
- javascript - addEventListener 是否采用注册 eventListener 时的值以供将来执行?
- python - TypeError:“模块”对象不可调用(在python中)
- javascript - 如何仅将 DOMParser 结果的特定部分附加到 DocumentFragment 元素
- reactjs - 在 React js 中显示本地图像并将其保存到数据库中
- javascript - 我正在尝试从谷歌电子表格发送一封电子邮件,但是该邮件并未复制超链接