Skip to content

Instantly share code, notes, and snippets.



Last active Jul 8, 2018
What would you like to do?
Automatically Save emails to a folder using, AppleScript, and Bash.

How to get it to work.

NOTE: This is mac only.

  1. Go to Finder.
  2. Press CMD+SHIFT+G.
  3. Type ~/Library/Application Scripts/
  4. Open saveByRule.scpt and change theFolder to where you'd like emails to be saved.
  5. Copy and Paste saveByRule.scpt into ~/Library/Application Scripts/
  6. Go to Mail>Preferences>Rules>Add Rule.
  7. Enter some filter for your rule and choose Run Applescript as action to perform. Use saveByRule as option.
  8. Click Ok.

For converting to PDF and HTML.

  1. In the terminal, run sudo pip install mail-parser and brew install Caskroom/cask/wkhtmltopdf.
  2. Open and alter location to match the directory your saved emails are located. (Keep *.eml)
  3. In the terminal, run bash

For Automating conversion to HTML/PDF.

  1. Create new>Folder Action in Automator.
  2. Set folder to watch to folder where emails are saved.
  3. Add run shell script action.
  4. Copy and paste contents of into textarea of run shell script.
  5. Save.

NOTE: saveByRule.scpt is almost entirely copied from StackOverflow.

using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
set msgs to selection
if length of msgs is not 0 then
set theFolder to (system attribute "HOME") & "/Downloads/"
repeat with msg in msgs
set msgContent to source of msg
-- determine date received of msg and put into YYYY-MM-DD format
set msgDate to date received of msg
-- parse date SEMversion below using proc pad2()
set {year:y, month:m, day:d, hours:h, minutes:min} to (msgDate)
set msgDate to ("" & y & "-" & my pad2(m as integer) & "-" & my pad2(d))
-- assign subject of msg
set msgSubject to (subject of msg)
-- create filename.eml to be use as title saved
set newFile to (msgDate & "-" & msgSubject & ".eml") as rich text
set newFilePath to theFolder & newFile as rich text
set referenceNumber to open for access newFilePath with write permission
write msgContent to referenceNumber
delete msg
on error
close access referenceNumber
end try
close access referenceNumber
end repeat
end if -- msgs > 0
end tell
end perform mail action with messages
end using terms from
on pad2(n)
return text -2 thru -1 of ("00" & n)
end pad2
# if [ -z $(pip list | grep -F "mail-parser" ) ]; then
# pip install mail-parser || sudo pip install mail-parser
# fi
# if [ -z $(brew cask list | grep -F "wkhtmltopdf" ) ]; then
# brew install Caskroom/cask/wkhtmltopdf
# fi
for file in $location/*.eml;
echo $file
echo "$noml"
mailparser -f $file -b > $location/$noeml.html
wkhtmltopdf $location/$x $location/$noeml.pdf
# Uncomment any these if you'd prefer not to keep a file type.
# rm -f *.eml
# rm -f *.html
# rm -f *.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment