6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google Apps ScriptAdvent Calendar 2012

Day 22

個人的にほしいサービスはGASで簡単に作ってみよう

Last updated at Posted at 2012-12-22

すみませんQiitaの投稿に手間取ってしまいました。多分そのうち書き直します雑でごめんなさい。

GoogleAppScriptの有用性については、ここまでのGASAC2012で他のみなさんが教えてくださっていますので、自分がどのように活用しているか公開することで「プログラム組めるならGASを自分のために使ってみては?」と提案したいです。
GASの利用にはGoogleアカウントが必要で、
認証が必要なサービスへの最初のアクセス時に自分で認証する必要あったりしますが、
GASで作った自分用のサービスは自分だけが利用者で、好きなように出来るのはもちろん、
気兼ねなく自分の認証で必要なサービスにつないでも安全(自分の作り次第)です。

というわけで、自分の場合ガラケーのメール定額を活用するため、
メールだけで自分のGmailを検索して結果を返すサービスを作りました。
(本当はmixiやfacebookの人の投稿にメールでコメントつけたりできる機能も作りたいけど、まだ何も手がついてません。URLからWebを携帯用にテキストに分割してメールで返す機能は作りかけています。)
またGASは基本的にGoogleDrive上にIDE?があり専用エディタで編集するようになっていますが、
GASLoaderなるすばらしいツールがライブラリとして公開されているので、それを使えばGitHub(Gist)やGoogleDriveにアップしたソーステキストを取り込んで実行できます。
ってことでメールでGoogleDriveにソースをアップする機能も作ってみました。

みなさんも自分の必要に応じて、何でも小さなところから始められることをお勧めします。

現時点でのソースは以下のような感じです、GASの仕様が変わったのか一部動かないところがありますがご了承ください。いずれ直します。

toPlainText.js
function toPlainText(html) {
return toText(Xml.parse(html, true).getElement());
}

function toText(element) {
var str;
switch(element.toString()) {
case 'XmlText': 
str = element.toXmlString();
return str;
case 'XmlElement': 
return element.getNodes().map(toText).join('');
default: 
str = '';
if(element.toXmlString().substring(0,4)==('href')){
str = element.toXmlString().replace('"','').replace('href=','');
str = ' (link:' + str + ') ';
return str;
}
}
}
SearchGmail.js/0B961KPjnibE4aGxFa2F2Vjl6ZzQ
function searchGmail() {
try{
//**前処理*/
if(!GmailApp.getUserLabelByName('donegmail')){
GmailApp.createLabel('donegmail');
}
var done = GmailApp.getUserLabelByName('donegmail');
var now = new Date();
var today = Utilities.formatDate(new Date(),'Asia/Tokyo','yyyy/MM/dd');
var reqfrom = Session.getEffectiveUser().getEmail();
var query = '-in:trash to:' + reqfrom.split('@')[1] + ' -label:donegmail after:' + Utilities.formatDate(new Date(new Date(now.getFullYear(),now.getMonth(),now.getDate()-1)),'Asia/Tokyo','yyyy/MM/dd');
var threads = GmailApp.search(query);
var opt = {noReply: true};
var resbody,resmsgs,resmsg,resmsgslen;
var id,date,from,to,subject,body;
var file,errorlog;
if(threads.length>0){
for(var threadsidx in threads){
var thread = threads[threadsidx];
var reqmsgs = thread.getMessages();
var reqmsg = reqmsgs[0];
if(reqmsg.isInTrash()){
continue;
}
var reqTo = reqmsg.getTo();
//**URLブラウズ*/
if(reqTo.indexOf('browse') > 0){
var url = toPlainText(reqmsg.getBody().split('\n')[0]);
var page = (reqmsg.getSubject())*1;
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
var response = UrlFetchApp.fetch(url);
var restext = toPlainText(response.getContentText().replace(/<!--(.|\n)*-->/g,''));
if(restext.length > page*3000){
resbody = restext.slice(page*3000,page*3000+3000);
} else {
resbody = '<EOF>';
}
Logger.log('\n' + today + ':browse(' + page + '/' + Math.ceil(restext.length / 3000) + ')[' + restext.length + ']:\n' + url);
CacheService.getPrivateCache().put('SearchGmailLog',Logger.getLog(),60*60);
resbody =resbody + '\n\n実行ログ\n' + CacheService.getPrivateCache().get('SearchGmailLog');
//GmailApp.sendEmail(reqmsg.getFrom(),'Re: Browse',resbody,opt);
opt.htmlBody = response.getContentText();
GmailApp.sendEmail(reqmsg.getFrom(),'Re: Browse',resbody,opt);
//**ソース保存*/
} else if(reqTo.indexOf('putsource') > 0){
var fname = toPlainText(reqmsg.getSubject());
var source = toPlainText(reqmsg.getBody());
file = DocsList.find('title:' + fname)[0];
if(!file){
DocsList.createFile(fname,source);
} else {
file.makeCopy();
file.replace(source);
}
resbody = source;
Logger.log('\n' + today + ':putsource:' + fname + '/\n' + resbody);
GmailApp.sendEmail(reqmsg.getFrom(),'Re: PutSource:'+ fname,resbody,opt);
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
//**ソース取得*/
} else if(reqTo.indexOf('getsource') > 0){
//file = DocsList.getFileById('0B961KPjnibE4dm44dHYzRmdKZ0U');
file = DocsList.find('title:toPlainText.js')[0];
resbody = file.getContentAsString().replace(/  /g,'');
Logger.log('\n' + today + ':getsource:toPlainText.js\n' + resbody);
GmailApp.sendEmail(reqmsg.getFrom(),'Re: GetSource:' + file.getName(),resbody,opt);
//file = DocsList.getFileById('0B961KPjnibE4aGxFa2F2Vjl6ZzQ');
file = DocsList.find('title:SearchGmail.js')[0];
resbody = file.getContentAsString().replace(/  /g,'');
Logger.log('\n' + today + ':getsource:SearchGmail.js\n' + resbody);
GmailApp.sendEmail(reqmsg.getFrom(),'Re: GetSource:' + file.getName(),resbody,opt);
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
//**Gmail検索*/
} else if(reqTo.indexOf('searchgmail') > 0){
query = toPlainText(reqmsg.getBody().split('\n')[0]);
Logger.log('\n' + today + ':searchgmail:' + query);
CacheService.getPrivateCache().put('SearchGmailLog',Logger.getLog(),60*60);
if(query !== ''){
resbody = '\n検索条件:' + query +'\n\n要求を受け付けました\nしばらくおまちください\n' + today;
errorlog = CacheService.getPrivateCache().get('SearchGmailLog');
if(errorlog !== ''){
resbody = resbody +'\n実行ログ\n' + errorlog;
CacheService.getPrivateCache().remove('SearchGmailLog');
}
GmailApp.sendEmail(reqmsg.getFrom(),'Re: SearchGmail',resbody,opt);CacheService.getPrivateCache().remove('SearchGmailLog');
resbody = '\n検索条件:' + query +'\n';
var result = GmailApp.search(query,0,100);
if(result.length < 1){
resbody = resbody + '\n条件に該当するメールは\n見つかりませんでした\n';
}
resbody = resbody + '検索結果 ' + result.length + '件\n';
var cnt = 1;
resbody = resbody + '\n';
var imax = result.length;
for (var i = imax; i>= 1; i--) {
var resthre = result[i-1];
resmsgs = resthre.getMessages();
var resid = resthre.getId();
var labels = resthre.getLabels();
resmsgslen = resmsgs.length;
var labelslen = labels.length;
resbody = resbody + '\n****';
if(resmsgslen > 1){
resbody = resbody + '(' + resmsgslen + ')id:' + resid + '\n' + reqfrom.split('@')[0] + '+getgmail' +resid + '@' + reqfrom.split('@')[1];
}
if(labelslen > 0){
resbody = resbody + '\nlabel:';
for (var j = 0; j < labelslen; j++) {
resbody = resbody + labels[j].getName() + ' ';
}
}
resmsg = resmsgs[resmsgslen-1];id = resmsg.getId();
date = Utilities.formatDate(resmsg.getDate(),'Asia/Tokyo','yyyy/MM/dd(EE)HH:mm:ss');
from = resmsg.getFrom();
to = resmsg.getTo();
subject = toPlainText(resmsg.getSubject());
resbody = resbody + '\ndate:' + date + '\nsubject:' + subject + '\nfrom:' + from + '\nto:' + to + '\nid:' + id + '\n' + reqfrom.split('@')[0] + '+viewgmail' + id + '@' + reqfrom.split('@')[1] + '\n\n';
cnt = cnt + 1;
if(cnt > 20){
resbody = resbody + '検索結果が20件以上です。先頭20件を表示します。\n';
break;
}
}
errorlog = CacheService.getPrivateCache().get('SearchGmailLog');
if(errorlog !== ''){
resbody = resbody +'\n実行ログ\n' + errorlog;
CacheService.getPrivateCache().remove('SearchGmailLog');
}
GmailApp.sendEmail(reqmsg.getFrom(),'Re: SearchGmail',resbody,opt);
} else {
resbody = '演算子\n/検索条件\n' +'from:\n/送信者\n' +'to:\n/受信者\n' +'subject:\n/件名に含まれる単語\n' +'OR\n/いずれかに一致\n' +'-\n/除外ワード\n' +'label:\n/ラベル\n' +'has:attachment\n/添付ファイル付き\n' +'list:\n/メーリングリスト\n' +'filename:\n/添付ファイル名\n' +'" "\n/フレーズ\n' +'( )\n/グループ化\n' +'in:anywhere\n/すべてのメール\n' +'in:inbox\n/[受信トレイ]\n' +'in:trash\n/[ゴミ箱]\n' +'in:spam\n/[迷惑メール]\n' +'is:important\n/重要\n' +'is:starred\n/スター付き\n' +'is:unread\n/未読\n' +'is:read\n/既読\n' +'cc:\n/[Cc]\n' +'bcc:\n/[Bcc]\n' +'after:\nbefore:\n/yyyy/mm/dd期間指定\n' +'deliveredto:\n/Delivered-Toヘッダ\n' +'is:chat\n/チャットメッセージ\n' +'-in:spam -in:trash -is:sent -in:drafts -in:inbox' +'\n/アーカイブ検索\n';
GmailApp.sendEmail(reqmsg.getFrom(),'Re: SearchGmail',resbody,opt);
}
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
//**スレッド取得*/
} else if(reqTo.indexOf('getgmail') > 0){
var thid = reqTo.split('@')[0].split('getgmail')[1];
Logger.log('\n' + today + ':getgmail:' + thid);
CacheService.getPrivateCache().put('SearchGmailLog',Logger.getLog(),60*60);
Logger.log('\n' + thid);
resmsgs = GmailApp.getThreadById(thid).getMessages();
Logger.log('\n' + resmsgs.length);
resmsgslen = resmsgs.length;
resbody ='\n';
for(var resmsgsidx in resmsgs){
resmsg = resmsgs[resmsgsidx];
id = resmsg.getId();
date = Utilities.formatDate(resmsg.getDate(),'Asia/Tokyo','yyyy/MM/dd(EE) HH:mm:ss');
from = resmsg.getFrom();
to = resmsg.getTo();
subject = toPlainText(resmsg.getSubject());
body = toPlainText(resmsg.getBody()).slice(0, 250);
resbody = resbody + '****(' + (resmsgsidx*1+1) + '/' + resmsgslen +') id:' + id + '\n' + reqfrom.split('@')[0] + '+viewgmail' +id + '@' + reqfrom.split('@')[1] + '\ndate:' + date + '\nsubject:' + subject + '\nfrom:' + from + '\nto:' + to + '\n' + body + '...\n\n';
}
errorlog = CacheService.getPrivateCache().get('SearchGmailLog');
if(errorlog !== ''){
resbody = resbody +'\n実行ログ\n' + errorlog;
CacheService.getPrivateCache().remove('SearchGmailLog');
}
GmailApp.sendEmail(reqmsg.getFrom(), 'Re: GetGmail', resbody,opt);
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
break;
//**メール表示*/
} else if(reqTo.indexOf('viewgmail') > 0){
id = reqTo.split('@')[0].split('viewgmail')[1];
Logger.log('\n' + today + ':viewgmail:' + id);
CacheService.getPrivateCache().put('SearchGmailLog',Logger.getLog(),60*60);
Logger.log('\n' + id);
resmsg = GmailApp.getMessageById(id);
var folder = DocsList.getFolder('email_attachments');
var files = folder.getFiles();
for(var l in files){
files[l].setTrashed(true);
}
date = Utilities.formatDate(resmsg.getDate(),'Asia/Tokyo','yyyy/MM/dd(EE) HH:mm:ss');
from = resmsg.getFrom();
to = resmsg.getTo();
subject = toPlainText(resmsg.getSubject());
body = toPlainText(resmsg.getBody());
var attachments = resmsg.getAttachments();
var cc = resmsg.getCc();

resbody = '\nid:' + id + '\n' + 'date:' + date + '\nsubject:' + subject + '\nfrom:' + from + '\nto:' + to;
if(cc !== ''){
resbody = resbody + '\ncc:' + cc;
}
resbody = resbody + '\n' + body.slice(0,1000);
if(body.length > 1000){
resbody = resbody + '...';
}
if(attachments.length > 0){
resbody = resbody + '\nattachment:\n';
for (var k in attachments) {
var attachment = attachments[k];
folder = DocsList.getFolder('email_attachments');
var attfile = folder.createFile(attachment.getAs(attachment.getContentType()));
var atturl = attfile.getUrl();
resbody = resbody + attachment.getName() + '\n' + atturl + '\n';
}
}
resbody = resbody + '\n';
errorlog = CacheService.getPrivateCache().get('SearchGmailLog');
if(errorlog !== ''){resbody = resbody +'\n実行ログ\n' + errorlog;
CacheService.getPrivateCache().remove('SearchGmailLog');
}
GmailApp.sendEmail(reqmsg.getFrom(), 'Re: ViewGmail', resbody,opt);
reqmsg.moveToTrash();
reqmsg.markRead();
done.addToThread(thread);
break;
}
}
}
//**エラー処理*/
}catch(e){
Logger.log(e);
CacheService.getPrivateCache().put('SearchGmailLog',Logger.getLog(),60*60);
}
}
function Executor() {
  var toPlainTextkey = DocsList.find('title:toPlainText.js')[0].getId();
  var SearchGmailkey = DocsList.find('title:SearchGmail.js')[0].getId();
  Logger.log(Utilities.jsonStringify(this).match(/function ([a-zA-Z]*)/g));
  GasLoader 
    .setMyCache(CacheService.getPrivateCache())
    .setLogLevel(GasLoader.LOG_LEVEL_ERROR())
    .requireFromDocs(toPlainTextkey,0)
    .requireFromDocs(SearchGmailkey,0)
    .searchGmail();
}
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?