Apple Mail.app の重複メールを何とかする

Appleのメール.appにはメールの重複を解決してくれる機能がありません。積もり積もった重複メールを抽出したりまとめて削除するためのAppleScriptです。

Apple の Mail.app で重複メールが作られてしまう原因はさまざまです。例えばTimeMachineから復帰させた時、「修復されたメッセージ」という謎フォルダが大量に作られたりして手動で受信箱に戻した時、iCloud のトラブル時などです。

理由はどうあれ受信箱の中で重複メールが発生し、数が多い場合には手動でどうにかできるレベルにありません。そしてApple Mail.appには重複メールを抽出する機能が備わっていません。

AppleScriptで何とかできないかと試作してきましたがド素人なので上手く書けず暗礁に乗り上げていました。

AI に作って貰おうとしても出てくるのは出来損ないばかりで何度修正を促してもまったく使い物になりません。AIなんてネットの受け売りしかできないただの阿呆と諦めていましたが、ChatGPTもバージョン上がったり日々進化しているので、また久しぶりに試してみました。

「もしもし」
「はいはいこんにちは」
「受信箱の重複メールを何とかしてくれるAppleScript作ってほしいんだけど」
「何とかしてくれで何とかなるほど世の中甘くないんだよ」

そんな会話はしていませんが、ついにまともに動くスクリプトを作ってくださいました。

受信箱を特定するために目的受信箱のメールを1つ選択しておいてからスクリプトを走らせると、重複メールを見つけてサブフォルダ「duplicate」に移動させます。

重複メールを duplicate フォルダに移動するスクリプト
-- Mail.app で選択中の受信箱を対象に重複メールを探す
-- 判定基準: message id
-- 重複メールを受信箱のサブフォルダ duplicate に移動

-- タイムアウトをデフォルトの120から大幅に増やしておく
with timeout of 1800 seconds
	
	
	tell application "Mail"
		-- 選択中のメッセージを取得
		set selMsgs to selection
		if selMsgs is {} then
			display dialog "対象となる受信箱を決めるために、メールを1通選択してください。" buttons {"OK"} default button 1
			return
		end if
		
		-- 最初に選択されたメッセージの所属メールボックスを基準にする
		set targetBox to mailbox of item 1 of selMsgs
		set targetAccount to account of targetBox
		
		-- そのメールボックス内のすべてのメッセージを取得
		set theMessages to messages of targetBox
		
		set seenIDs to {}
		set dupList to {}
		
		repeat with aMessage in theMessages
			try
				set mid to message id of aMessage
			on error
				set mid to ""
			end try
			
			if mid is not "" then
				if seenIDs contains mid then
					set end of dupList to aMessage
				else
					set end of seenIDs to mid
				end if
			end if
		end repeat
	end tell
	
	-- 結果を表示して移動確認
	set dupCount to (count of dupList)
	if dupCount is 0 then
		display dialog "重複メールは見つかりませんでした。" buttons {"OK"} default button 1
	else
		set msgText to "重複メールが " & dupCount & " 件見つかりました。
移動しますか?"
		set userChoice to button returned of (display dialog msgText buttons {"キャンセル", "移動"} default button "移動")
		
		if userChoice is "移動" then
			tell application "Mail"
				-- duplicate メールボックスを探す or 作成
				set dupBox to missing value
				repeat with mb in mailboxes of targetAccount
					if name of mb is "duplicate" then
						set dupBox to mb
						exit repeat
					end if
				end repeat
				
				if dupBox is missing value then
					set dupBox to make new mailbox at targetAccount with properties {name:"duplicate"}
				end if
				
				-- 重複メールを移動
				repeat with d in dupList
					move d to dupBox
				end repeat
			end tell
			display dialog "重複メールを「duplicate」フォルダへ移動しました。" buttons {"OK"} default button 1
		end if
	end if
	
end timeout

受信箱にサブフォルダ”duplicate”を作るので、それが可能ならコピペで動くと思います。

スクリプトエディタに保存して直接実行するなり、Automatorのクイックアクションを作ってサービスメニューに加えたりして使います。

注意事項:尚、検証を深めたスクリプトではないため、使ってみたい人はスクリプト内容をよく見て慎重かつ覚悟を持ってお願いします。何らかのエラーに見舞われた場合でも、当方は一切の責任は負いません。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください