Skip to content

Instantly share code, notes, and snippets.

@kaias1jp
Created May 17, 2021 13:12
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 kaias1jp/cbb66079059141935c69c45879d8d20c to your computer and use it in GitHub Desktop.
Save kaias1jp/cbb66079059141935c69c45879d8d20c to your computer and use it in GitHub Desktop.
IFTTTでOneDriveにあるファイルの情報を書いたメールをGmail API経由で取得してローカルに保存するスクリプト
#!/bin/bash
CLIENTID="<<Client ID>>"
CLIENTSECRET="<<Client Sercret>>"
REFRESHTOKEN="<<Refresh Token>>"
LABELID="<<Gmail LabelLabel ID>>"
#ファイルを保存するディレクトリに移動
cd <<Saved Directory>>
#Session IDと書いているが本当はAccess Tokenを毎回取っている
SESSIONID=`curl -d "client_id=$CLIENTID&client_secret=$CLIENTSECRET&refresh_token=$REFRESHTOKEN&grant_type=refresh_token" https://accounts.google.com/o/oauth2/token|jq .access_token|tr -d '"'`
#Gmailの特定ラベルの一覧のうち、一番最新のメールのIDを取得する
ID=`curl -H "Authorization: Bearer $SESSIONID" https://www.googleapis.com/gmail/v1/users/me/messages/?labelIds=$LABELID|jq .messages[0].id|tr -d '"'`
#SnippetにIFTTTの短縮URLがあるのでそれを取得
SP=`curl -H "Authorization: Bearer $SESSIONID" https://www.googleapis.com/gmail/v1/users/me/messages/$ID|jq .snippet|cut -d " " -f 1|tr -d '"'`
#IFTTTの短縮URLを取ったらHTMLの中にOneDriveのファイルを取得できるURLが入っているので取り出す
IFTTT=`curl $SP|cut -d "=" -f 2-|cut -d '"' -f 2|sed -n 3P`
#メールのHeaderからSubjectを取り出す。IFTTTでOneDriveのファイル名を設定するようにしている
SUBJECT=`curl -H "Authorization: Bearer $SESSIONID" https://www.googleapis.com/gmail/v1/users/me/messages/$ID|jq '.payload.headers[]|select (.name=="Subject")|.value'|cut -d '"' -f 2`
#取ろうとしているファイル名の付いたファイルがなければwgetで取ってきてSubjectの文字列をファイル名にして保存する
if [[ ! -e $SUBJECT ]]; then
wget -O "$SUBJECT" "$IFTTT"
else
echo "not save file($SUBJECT)"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment