如何在Javascript中设置通过Gmail Api发送邮件的权限?
How to set authorization for sending mail through Gmail Api in Javascript?
我正尝试在 javascript 中使用 Gmail Api 发送邮件,但出现 401 错误(需要登录)。我的应用程序已经获得授权,我有一个访问令牌。
这是我正在尝试的一段代码 运行:
gapi.client.load('gmail', 'v1',
var email = ''{my mail content};
var sendRequest = gapi.client.gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
}
});
return sendRequest.execute(callback);
});
请帮我做什么?提前致谢。
考虑到您是从前端发送消息,您并不真的需要使用客户端库。您可以只使用 JQuery 或类似的东西:
// You can test with your own account by getting a token here:
// https://developers.google.com/oauthplayground/
var accessToken = 'ya29...';
// Base64-encode the mail and make it URL-safe
// (replace all '+' with '-' and all '/' with '_')
var encodedMail = btoa([
'From: sender@gmail.com\r\n',
'To: receiver@gmail.com\r\n',
'Subject: Subject Text\r\n\r\n',
'Message Text'
].join('')).replace(/\+/g, '-').replace(/\//g, '_');
$.ajax({
method: 'POST',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages/send',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
data: JSON.stringify({
'raw': encodedMail
})
});
您可以只对邮件进行编码,然后先在 API explorer 中尝试。
我正尝试在 javascript 中使用 Gmail Api 发送邮件,但出现 401 错误(需要登录)。我的应用程序已经获得授权,我有一个访问令牌。
这是我正在尝试的一段代码 运行:
gapi.client.load('gmail', 'v1',
var email = ''{my mail content};
var sendRequest = gapi.client.gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
}
});
return sendRequest.execute(callback);
});
请帮我做什么?提前致谢。
考虑到您是从前端发送消息,您并不真的需要使用客户端库。您可以只使用 JQuery 或类似的东西:
// You can test with your own account by getting a token here:
// https://developers.google.com/oauthplayground/
var accessToken = 'ya29...';
// Base64-encode the mail and make it URL-safe
// (replace all '+' with '-' and all '/' with '_')
var encodedMail = btoa([
'From: sender@gmail.com\r\n',
'To: receiver@gmail.com\r\n',
'Subject: Subject Text\r\n\r\n',
'Message Text'
].join('')).replace(/\+/g, '-').replace(/\//g, '_');
$.ajax({
method: 'POST',
url: 'https://www.googleapis.com/gmail/v1/users/me/messages/send',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
data: JSON.stringify({
'raw': encodedMail
})
});
您可以只对邮件进行编码,然后先在 API explorer 中尝试。