AppleScriptでメールの振り分けをしてみる
AppleScriptとかAutomatorとかでもっと便利にMacを使いこなしたいなと思いませんか?
会社でメールの受信量が非常に多くて、メールボックスが重くなってしまったりします。
ルールで振り分けもしているのですがいちいち専用のメールボックスをつくってルール追加してというのが非常に面倒くさいし、効率が良くないと思ってました。
そこで、
* メールの送信日時を元にして、YYYY-MM 形式のメールボックスに振り分ける
* MLとか送信者とかでの抽出はスマートメールボックスを使って行って、必要なくなったら消しちゃう
* 古い送信日時のメールが入っているメールボックスはバックアップするか、削除しちゃう
こんな運用をしようと考えました。
ここで、メールのルール機能でできないのが「送信日時ごとのメールボックスへの振り分け」です。
ここをAppleScriptを使ってやってみようという試み。
以下にソースコードを貼ります。イマイチパフォーマンスが良くない感じもします。。
(*
Apple Mailで選択中のメールの送信日時をもとに、「YYYY/YYYY-MM」という名前のメールボックスに振り分けます。
メールボックスが存在しない場合は自動的に作成されます。
*)
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
repeat with theMessage in theMessages
if my isMovableMessage(theMessage) then
my mailHandler(theMessage)
end if
end repeat
end tell
end perform mail action with messages
end using terms from
on isMovableMessage(theMessage)
tell application "Mail"
-- 迷惑メールは対象外にする。その他振り分けしたくない条件があればここに記載
if junk mail status of theMessage then return false
return true
end tell
end isMovableMessage
on mailHandler(theMessage)
tell application "Mail"
try
set theSent to date sent of theMessage
set theYear to (year of theSent) as string
set numMonth to month of theSent as number
set theMon to rich text -2 thru -1 of ("0" & (numMonth as rich text))
set theMonth to (theYear & "-" & theMon) as string
set thePath to (theYear & "/" & theMonth) as string
-- メールボックスが存在しなかったら作成する
if not (my makeMailbox(theYear, theYear)) then return
if not (my makeMailbox(theMonth, thePath)) then return
-- YYYY/YYYY-MM メールボックスへ移動する
set targetContainer to mailbox thePath
move theMessage to targetContainer
return true
on error errMsg
display dialog errMsg
return false
end try
end tell
end mailHandler
on makeMailbox(newName, newPath)
set theResult to true
tell application "Mail"
set checkList to (mailboxes whose name of it contains newName)
if checkList is equal to {} then
try
make new mailbox at beginning with properties {name:newPath}
on error errMsg
set theResult to false
display dialog "メールボックスの作成に失敗しました:" & (newPath as string) & return & errMsg
end try
end if
end tell
return theResult
end makeMailbox