Split mail by month in AppleScript and Mail.app

So my resurgent affair with AppleScript continues…
I was having to organise a fair bit of email, so came up with this AppleScript to split email by month.

This doesn't look at the year at all. You need to organise that on your own.

Basically it just takes the list of currently selected mailboxes in the front most window of Mail.app, and for each one, it creates a corresponding “[mailbox-name]-SplitByMonth” mailbox locally, and sub-folders for each month.

Save it to one of the Mail Scripts folders, ie ~/Library/Scripts/Mail Scripts/ and then use it from within Mail.app

using terms from application "Mail"
	display dialog ¬
		"This will split the currently selected mailboxes in the frontmost Mail.app window
		to new mailboxes by month." buttons {"Cancel", "Split Mailboxes"} ¬
		default button "Split Mailboxes"
	set splittingMailboxList to selected mailboxes of front message viewer
	repeat with splitThisMailbox in splittingMailboxList
		set shortMonthlist to {"01-Jan", "02-Feb", "03-Mar", "04-Apr", "05-May", "06-Jun", ¬
			"07-Jul", "08-Aug", "09-Sep", "10-Oct", "11-Nov", "12-Dec"}
		set fullMonthList to {"January", "February", "March", "April", "May", "June", "July", ¬
			"August", "September", "October", "November", "December"}
		set parentMailboxName to (name of splitThisMailbox) & "-SplitByMonth"
		tell application "Mail"
			try
				make new mailbox with properties {name:parentMailboxName}
			end try
			set mailboxMessages to every message of splitThisMailbox
			repeat with eachMessage in mailboxMessages
				set receievedDate to (date received of eachMessage) as string
				set monthIndex to 1
				repeat with eachFullMonth in fullMonthList
					if (receievedDate contains eachFullMonth) then
						set monthMailboxName to parentMailboxName & ¬
							"/" & (name of splitThisMailbox) & ¬
							"_" & (item monthIndex of shortMonthlist)
						try
							make new mailbox with properties {name:monthMailboxName}
						end try
						move eachMessage to mailbox monthMailboxName
					end if
					set monthIndex to monthIndex + 1
				end repeat
			end repeat
		end tell
	end repeat
end using terms from

Leave a Reply

Name and Email Address are required fields. Your email will not be published or shared with third parties.