Skip to content

Instantly share code, notes, and snippets.

@keithyipkw
Last active September 15, 2015 03:24
Show Gist options
  • Save keithyipkw/15e1f6c95af08dda5de1 to your computer and use it in GitHub Desktop.
Save keithyipkw/15e1f6c95af08dda5de1 to your computer and use it in GitHub Desktop.
AppleScript of exporting unread emails and attachments to a folder
set theOutputFolder to (choose folder) as string
tell application "Mail"
set theMessages to (messages of mailbox "mailbox name" of account "account name" whose read status is false)
repeat with theMessage in theMessages
try
set theSender to extract name from sender of theMessage
set {year:y, month:m, day:d, hours:h, minutes:min, seconds:s} to theMessage's date sent
set subFolder to ("" & theSender & " " & y & my pad(m as integer) & my pad(d) & "T" & my pad(h) & my pad(min) & my pad(s))
tell application "Finder"
if not (exists folder subFolder of folder theOutputFolder) then
make new folder at theOutputFolder with properties {name:subFolder}
end if
end tell
set subFolder to theOutputFolder & subFolder & ":"
set body to content of theMessage
set theFile to subFolder & "content.txt"
set theFileID to open for access file theFile with write permission
write body to theFileID
close access theFileID
repeat with theAttachment in theMessage's mail attachments
set theAttachmentName to name of theAttachment
set theSavePath to subFolder & theAttachmentName
save theAttachment in theSavePath
end repeat
set read status of theMessage to true
end try
end repeat
end tell
on pad(n)
return text -2 thru -1 of ("00" & n)
end pad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment