我一直在编写一个客户端(Chrome浏览器)应用程序,它通过REST API与GMail集成。我的应用程序是用Javascript / Angular编写的,大多数GMail集成工作正常。它可以从GMail中获取 - 电子邮件,个人资料,标签等。
我无法发送我创建的电子邮件。但是,我尝试发送的电子邮件会显示在GMail发送列表中,如果我通过添加“收件箱”来修改电子邮件。标签,它们也出现在GMail收件箱中。但是没有一封电子邮件能够到达目的地。我一直在测试几个电子邮件帐户 - Hotmail,Yahoo和另一个GMail帐户。电子邮件从未发送到目的地 - 我已检查过收件箱,垃圾邮件等。
我的代码如下...功能' initializeGMailInterface'首先运行(通过用户界面)进行授权,然后运行“发送电子邮件”。功能(也通过用户界面)。该代码似乎跟踪了我已经看过的示例以及Google为其REST API提供的文档。身份验证似乎工作正常 - 正如我所提到的,我能够获取电子邮件等。
如何将电子邮件发送到目的地?
var CLIENT_ID = '853643010367revnu8a5t7klsvsc5us50bgml5s99s4d.apps.googleusercontent.com';
var SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.labels'];
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
loadGmailApi();
}
}
$scope.initializeGMailInterface = function() {
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: true
}, handleAuthResult);
};
function loadGmailApi() {
gapi.client.load('gmail', 'v1', function() {
console.log("Loaded GMail API");
});
}
$scope.sendEmail = function() {
var content = 'HELLO';
// I have an email account on GMail. Lets call it 'theSenderEmail@gmail.com'
var sender = 'theSenderEmail@gmail.com';
// And an email account on Hotmail. Lets call it 'theReceiverEmail@gmail.com'\
// Note: I tried several 'receiver' email accounts, including one on GMail. None received the email.
var receiver = 'theReceiverEmail@hotmail.com';
var to = 'To: ' +receiver;
var from = 'From: ' +sender;
var subject = 'Subject: ' +'HELLO TEST';
var contentType = 'Content-Type: text/plain; charset=utf-8';
var mime = 'MIME-Version: 1.0';
var message = "";
message += to +"\r\n";
message += from +"\r\n";
message += subject +"\r\n";
message += contentType +"\r\n";
message += mime +"\r\n";
message += "\r\n" + content;
sendMessage(message, receiver, sender);
};
function sendMessage(message, receiver, sender) {
var headers = getClientRequestHeaders();
var path = "gmail/v1/users/me/messages?key=" + CLIENT_ID;
var base64EncodedEmail = btoa(message).replace(/\+/g, '-').replace(/\//g, '_');
gapi.client.request({
path: path,
method: "POST",
headers: headers,
body: {
'raw': base64EncodedEmail
}
}).then(function (response) {
});
}
var t = null;
function getClientRequestHeaders() {
if(!t) t = gapi.auth.getToken();
gapi.auth.setToken({token: t['access_token']});
var a = "Bearer " + t["access_token"];
return {
"Authorization": a,
"X-JavaScript-User-Agent": "Google APIs Explorer"
};
}