Skip to content

Instantly share code, notes, and snippets.

@hatappi
Last active April 16, 2017 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hatappi/e373686417b4c456d06a7b7179bcbd18 to your computer and use it in GitHub Desktop.
Save hatappi/e373686417b4c456d06a7b7179bcbd18 to your computer and use it in GitHub Desktop.
function main() {
const threads = GmailApp.search('label:gcsエクスポート-未処理');
for(var i = 0; i < threads.length; i++) {
const messages = GmailApp.getMessagesForThread(threads[i]);
/* 各メールから日時、送信元、件名、内容を取り出す*/
const message = messages[messages.length - 1];
const attachments = message.getAttachments();
for(var j = 0; j < attachments.length; j++) {
if (attachments[0].getName() == "書き出す.zip") {
// GmailAttachment
isSuccess = uploadFile_(attachments[0]);
threads[i].removeLabel(yetLabel);
threads[i].addLabel(completeLabel);
}
}
}
}
function uploadFile_(gmailAttachment) {
const jsonKey = JSON.parse(PropertiesService.getScriptProperties().getProperty("SAJsonKey"));
const gsAPP = new GSApp.init(jsonKey.private_key, ['https://www.googleapis.com/auth/devstorage.full_control'], jsonKey.client_email);
const tokens = gsAPP.addUser(jsonKey.client_email).requestToken().getTokens();
const token = tokens[jsonKey.client_email].token;
const bucketName = '任意のバケット名';
const uploadFilepath = 'GCSへのアップロードパス exp: `hoge/fuga.zip`';
const requestUrl = "https://www.googleapis.com/upload/storage/v1/b/"+bucketName+"/o?uploadType=media&name="+encodeURIComponent(uploadFilepath);
const blob = gmailAttachment.copyBlob();
const bytes = blob.getBytes();
const fetchOptions = {
method: "POST",
contentLength: bytes.length,
contentType: blob.getContentType(),
payload: bytes,
headers:{Authorization:"Bearer "+ token}
};
UrlFetchApp.fetch(requestUrl, fetchOptions);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment