我们使用共同的学生信息系统来管理我们的学校。它很容易在客户端定制,有些地方我们想在某些动作发生时触发电子邮件(表单提交,页面加载等)。不可能使用PHP,ASP或Java等服务器端编程语言。
我们想要做的是使用AJAX调用来发送电子邮件。我完全使用JavaScript工作,但我必须使用我要发送的GMail帐户表单登录。我们需要对此进行一次身份验证(或者只要持有者令牌有效),然后在用户操作发生后发送电子邮件。
由于客户端语言似乎能够在没有发送帐户在浏览器会话中“登录”的情况下点击这些端点并发送电子邮件,这似乎对我来说。是吗?
我也意识到创建一个使用GMail作为SMTP中继的服务器端脚本是一种选择,但许多使用Google Apps for Education的学校根本没有可以托管此类脚本的网站服务器。客户端插件确实是我们想要构建的。
答案 0 :(得分:0)
您可以尝试此操作,只需替换 CLIENT_ID 值:
此范围是只读,但我可以根据您需要执行的操作进行更改。
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadGmailApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Gmail API client library. List labels once client library
* is loaded.
*/
function loadGmailApi() {
gapi.client.load('gmail', 'v1', listLabels);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
var request = gapi.client.gmail.users.labels.list({
'userId': 'me'
});
request.execute(function(resp) {
var labels = resp.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Gmail API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>