Skip to content

Instantly share code, notes, and snippets.

@lordsutch
Created July 1, 2019 16:55
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 lordsutch/dd4c4143220da68d1ab34bf50751dea9 to your computer and use it in GitHub Desktop.
Save lordsutch/dd4c4143220da68d1ab34bf50751dea9 to your computer and use it in GitHub Desktop.
AppleScript to save attachments into a folder with filenames including the attachment date
-- Tested on macOS 10.14.5
use scripting additions
using terms from application "Mail"
on perform mail action with messages messageList -- in mailboxes mbox for rule aRule
-- Must be in your Downloads folder or a subfolder in recent macOS versions
set destinationPath to (POSIX file "/Users/quango/Downloads/enrollment/") as string
tell application "Mail"
repeat with aMessage in messageList
-- Get the date the message was sent
set {year:y, month:m, day:d, hours:h, minutes:min} to aMessage's date sent
set timeStamp to ("" & y & my pad(m as integer) & my pad(d))
repeat with anAttachment in mail attachments of aMessage
set originalName to name of anAttachment
set baseName to my RemoveExtension(originalName)
set fileExt to my getExtension(originalName)
set attachmentName to (baseName & "-" & timeStamp & "." & fileExt)
save anAttachment in file (destinationPath & attachmentName)
end repeat
end repeat
end tell
end perform mail action with messages
end using terms from
-- Adds leading zeros to date components
on pad(n)
return text -2 thru -1 of ("00" & n)
end pad
on RemoveExtension(this_name)
-- This function comes from :
-- http://www.macosxautomation.com/applescript/sbrt/index.html
if this_name contains "." then
set this_name to (the reverse of every character of this_name) as string
set dot_offset to the offset of "." in this_name
set this_name to (text (dot_offset + 1) thru -1 of this_name)
set this_name to (the reverse of every character of this_name) as string
end if
return this_name
end RemoveExtension
on getExtension(this_name)
if this_name contains "." then
set this_name to (the reverse of every character of this_name) as string
set dot_offset to the offset of "." in this_name
set this_name to (text 1 thru (dot_offset - 1) of this_name)
set this_name to (the reverse of every character of this_name) as string
return this_name
else
return ""
end if
end getExtension
on logToConsole(txt)
do shell script "/usr/bin/logger -t \"Mail script:\" " & txt's quoted form
end logToConsole
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment