Step by Step!

logicbaseのブログ

カメラプリセットコントローラ「巡回くん」の添付画像を自動保存してみた^^ (Googleドライブ編)

f:id:logicbase:20140718093200j:plain
前回のカメラプリセットコントローラ「巡回くん」の添付画像を自動保存してみた^^ (Thunderbird編)ではメーラーThunderbird」とアドオン「AttachmentExtractor」の組み合わせでカメラプリセットコントローラ「巡回くん」のメール添付画像をローカルフォルダに保存する方法を説明しました。


今回は「巡回くん」のメール添付画像をGoogleドライブに自動保存してみます。
noriaki blog はてな出張所の記事を参考にさせていただきました)

概要

スクリプトは指定の送信元メールアドレスとメールタイトルに一致するメールの添付JPGファイルをGoogleドライブ(フォルダ名:GmailAttachments)に自動保存するスクリプトです。(「巡回くん」の巡回画像送信先メールアドレスにはGmailを指定します)

Google Apps スクリプト

Googleドライブ>作成>スクリプトで空プロジェクトを作成後、以下のスクリプトをコピペします。

/*
 
    Auto-Save your Gmail Image Attachments to Google Drive
    ======================================================

    Fork written by Akio Higuchi on 17/07/2014
    
    The default Google Drive folder for saving the image
    attachments is "GmailAttachments" match the email-add
    ress(to),email-address(from) and email-subject.
    once the message has been processed, Gmail applies the
    label "Processed" to that message.
    You can change the defaults in line 43 & 44.   


    Auto-Save your Gmail Image Attachments to Google Drive
    ======================================================
    
    Fork written by Noriaki Uchiyama on 11/05/2013 

    The default Google Drive folder for saving attachments
    is "GmailAttachments" only has GMail label "@gdrive" 
    and once the message has been processed, Gmail applies 
    the label "Processed" to that message.
    You can change the defaults in line 38 to 40.
    
    
    Auto-Save your Gmail Image Attachments to Google Drive
    ======================================================
 
    Written by Amit Agarwal on 05/28/2013 
    
    To get started, choose Run -> Authorize and grant the 
    necessary permissions. Then choose Run -> StartProgram. 
    
    The default Google Drive folder for saving the image
    attachments is "Gmail Images" and once the message has
    been processed, Gmail applies the label "Processed" to 
    that message. You can change the defaults in line 26 & 26.
 
*/
 
var FROM_MAIL_ADDRESS = "higuchi.akio@gmail.com"
var MAIL_SUBJECT = "[巡回]BB-HCM100"

// Authorize the Google Apps Script
function Authorize() {
  StartProgram();
}
 
// Initialize the Script
function StartProgram() {
  
  var DRIVE_FOLDER = "GmailAttachments";  
  var GMAIL_LABEL  = "Processed";
  
  createGmailLabel(GMAIL_LABEL);
  createDriveFolder(DRIVE_FOLDER);  
  createTrigger();
 
}
 
// The script will check your Gmail mailbox every minute
// with the help of a CLOCK based trigger.
function createTrigger() {
  
  var triggers = ScriptApp.getScriptTriggers();
  
  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }
  
  ScriptApp.newTrigger('saveGmailAttachments')
   .timeBased()
   .everyMinutes(1)
   .create();   
 
}
 
// If the Gmail label is unavailable, create one.
function createGmailLabel(name) {
  
  if ( ! GmailApp.getUserLabelByName(name) ) {
    GmailApp.createLabel(name);
  }
  
  ScriptProperties.setProperty("LABEL", name); 
}
 
 
// If the Google Drive folder is not present, create one.
function createDriveFolder(name) {
  
  var folders = DriveApp.getFolders();
  var folder, found = false;
 
  while (folders.hasNext()) {
    folder = folders.next();
    if (folder.getName() === name) {
      found = true;
      break;
    }
  }
  
  if ( ! found ) {
    DriveApp.createFolder(name);      
  }
  
  ScriptProperties.setProperty("FOLDER_ID", folder.getId()); 
}
 
// This will auto-save the image attachments from Gmail to Google Drive
function saveGmailAttachments() {
  
  var from_mailaddress = FROM_MAIL_ADDRESS;
  var mailsubject = MAIL_SUBJECT;
  
  var label_name = ScriptProperties.getProperty("LABEL");  
  var label = GmailApp.getUserLabelByName(label_name);   
  
  var folderID  = DriveApp.getFolderById(ScriptProperties.getProperty("FOLDER_ID"));
  
  // Scan for threads that have image attachments
  var threads = GmailApp.search("in:all -in:spam -in:trash -in:" + label_name
                                + " has:attachment filename:jpg"
                                + " from:" + from_mailaddress
                                + " subject:" + mailsubject
                                , 0, 10);      
  
  try {
    
    for (var x=0; x<threads.length; x++) {
      
      var messages = threads[x].getMessages();
      
      for (var y=0; y<messages.length; y++) {
        
        var attachments = messages[y].getAttachments();
        
        for (var z=0; z<attachments.length; z++) {
          
          var file = attachments[z];
          
          // Only save image attachments that have the MIME type as image.
          if (file.getContentType().match(/image/gi)) {
            folderID.createFile(file);
          }
        }       
      }
      // Process messages are labelled to skip them in the next iteration.
      threads[x].addLabel(label);
    }  
  }
  catch (e) {
    Logger.log(e.toString());
  }
}

43行目を送信元メールアドレス、44行目を「巡回くん」の送信メールタイトルに書き換えてください。

var FROM_MAIL_ADDRESS = "送信元メールアドレス"
var MAIL_SUBJECT = "「巡回くん」メールタイトル"


また、124行目あたりでGmailの検索を行っています。クエリを書き換えて検索条件をかえることができます。(Gmail 詳細検索の説明はこちら

スクリプトに権限付与

スクリプトGmailGoogleドライブの権限を付与します。
f:id:logicbase:20140718083551j:plain

スクリプトを定期実行

スクリプトを定期実行させます。
f:id:logicbase:20140718083802j:plain
これで本スクリプトが1分毎に自動実行され「巡回くん」から送信されたメールの添付画像がGoogleドライブ上の「GmailAttachments」というフォルダに自動保存されるようになります。

もちろんスマートフォンでも

Googleドライブに画像が自動でUPされるので外出先でも簡単に画像を時系列で確認できイイ感じです。
f:id:logicbase:20140718085744j:plain

スクリプトの定期実行をストップさせたい場合

スクリプトの実行を停止したい場合は次のように操作してトリガーを削除してください。

リソース>現在のプロジェクトのトリガーをクリック
f:id:logicbase:20140718084138j:plain

xをクリックして現在のトリガー(saveGmailAttachments)を削除します。
f:id:logicbase:20140718084145j:plain
これでスクリプトの定期実行はストップします。