Mail Server Solution(6)Email Scan and Auth on Client

使用Gmail API下载邮件附件
本文详细介绍了如何使用Gmail JavaScript API从客户端下载邮件附件,包括设置环境、权限验证、消息查询、消息获取和附件下载等关键步骤。
Mail Server Solution(6)Email Scan and Auth on Client

1. Does Gmail API Support Forwarding, NO
We can set up customer filter manually
https://support.google.com/mail/answer/6579?hl=en

We can use the admin SDK to set up filter for enterprise domain account with the administrator user.
https://developers.google.com/admin-sdk/email-settings/

Or we need to download the email content and send a new email ourselves.

2. Scan the Email and Download the Attachment from Client
I plan to use JavaScript. Here is the list
https://developers.google.com/api-client-library/

Here is the API for javascript.
https://developers.google.com/api-client-library/javascript/
https://developers.google.com/api-client-library/javascript/samples/samples

Gmail API JavaScript Client
https://developers.google.com/gmail/api/quickstart/js

3. Set up Env
Check the python version. Life is short, let’s use python. haha.
> python -V
Python 2.7.6

Create a very simple html file index.html
> cat index.html
Hello, Sillycat.

This will start the web server
> python -m SimpleHTTPServer 8000

We can visit the page for testing
http://localhost:8000/index.html

4. Gmail JavaScript API Implementation
<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 = ‘xxxxx';

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,
'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);
gapi.client.load('gmail', 'v1', function(){
listMessages("me", "craigslist.org has:attachment larger:50K", messageQueryCallback);
});
}

function messageQueryCallback(res){
//console.log("message query response:" + JSON.stringify(res, null, 4));
gapi.client.load('gmail', 'v1', function(){
getMessage("me", “xxxxxx", getMessageCallback);
});
}

function getMessageCallback(res){
//console.log("message get response:" + JSON.stringify(res.payload.parts, null, 4));
var parts = res.payload.parts;
for(var i = 0; i < parts.length; i++){
//console.log("message get response:" + JSON.stringify(parts[i].mimeType));
var type = parts[i].mimeType;
if( type === 'application/pdf' || type === 'application/doc'){
//console.log("message get response:" + JSON.stringify(parts[i].body.attachmentId));
var attachmentId = JSON.stringify(parts[i].body.attachmentId);
console.log("attachment get response:" + attachmentId);
var attachmentId = “xxxxxxx";
gapi.client.load('gmail', 'v1', function(){
getAttachments("me", attachmentId, “xxxxxx", getAttachmentCallback);
});

}
}
}

function getAttachmentCallback(res){
//console.log("attachment get response:" + JSON.stringify(res.data, null, 4));

}

function getAttachments(userId, attachmentId, messageId, callback) {
var request = gapi.client.gmail.users.messages.attachments.get({
'id': attachmentId,
'messageId': messageId,
'userId': userId
});
request.execute(function(attachment) {
callback(attachment);
});
}

/**
* Get Message with given ID.
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} messageId ID of Message to get.
* @param {Function} callback Function to call when the request is complete.
*/
function getMessage(userId, messageId, callback) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
});
request.execute(callback);
}

/**
* Retrieve Messages in user's mailbox matching query.
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} query String used to filter the Messages listed.
* @param {Function} callback Function to call when the request is complete.
*/
function listMessages(userId, query, callback) {
var getPageOfMessages = function(request, result) {
request.execute(function(resp) {
result = result.concat(resp.messages);
var nextPageToken = resp.nextPageToken;
if (nextPageToken) {
request = gapi.client.gmail.users.messages.list({
'userId': userId,
'pageToken': nextPageToken,
'q': query
});
getPageOfMessages(request, result);
} else {
callback(result);
}
});
};
var initialRequest = gapi.client.gmail.users.messages.list({
'userId': userId,
'q': query
});
getPageOfMessages(initialRequest, []);
}


/**
* 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>


References:
Mail Server Solution 1 ~ 5
http://sillycat.iteye.com/blog/2228923
http://sillycat.iteye.com/blog/2229222
http://sillycat.iteye.com/blog/2230801
http://sillycat.iteye.com/blog/2232877
http://sillycat.iteye.com/blog/2232889

http://stackoverflow.com/questions/24908700/mail-attachment-wrong-media-type-gmail-api
https://developers.google.com/gmail/api/guides/sending

https://developers.google.com/admin-sdk/email-settings/#manage_filters
https://developers.google.com/admin-sdk/email-settings/

https://developers.google.com/identity/sign-in/web/

meteor library load
http://stackoverflow.com/questions/22723300/how-do-you-include-3rd-party-javascript-libraries-in-meteor-js
https://atmospherejs.com/slava/gmail
package meteor library myself
http://www.meteorpedia.com/read/Packaging_existing_Libraries
https://github.com/MeteorCommunity/discussions/issues/14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值