Applescript to open Mail.app and attach a zip of some files

Nov 21, 2011 12:01


Every once in a while, while you're working on something, you find that all the available solutions to a task are horrendously out of date. After bashing my head against the problem, I eventually figured out the recipe that made things work, so I thought I'd post the solution here.

I was attempting to streamline the process of iterating on localization files. Being a member of the Engineering team, we wanted to make this as turn-key as possible on our end. The Localization team actually coordinates between several external contractors, who don't have access to our git repositories.

I knew I could construct a mailto: URL but that didn't have a clear way to attach files to the body of the e-mail. Being that our primary development computers are all running Mac OSX I figured Applescript would be the solution. I scoured the internet for solutions and it turned out that no sample code out there actually still worked for the problem at hand. Eventually I glued things together based on sample code from Apple and bits of several hints around the internet.

Most of the other e-mail applescripts I've seen fail to work on Leopard and all failed to fully work on Lion, so here is my sample code:

#!/bin/bash

target_address="example@example.com"
subject_stub="Daily Zip for files"

cwd=`pwd`
folderToZip="relative/path/from/here"
pathToZip= "build/DailyZip_"

/usr/bin/osascript <<-EOT

set cwd to "$cwd"

set {year:y, month:m, day:d} to (current date)
set datestr to y &"-" & (m*1) &"-" & d

set zipPath to cwd &"/$pathToZip" & datestr & ".zip"
log zipPath
set targetFilesPath to cwd & "/$folderToZip"
do shell script "zip -r -j " & zipPath & " " & targetFilesPath & ""

set att to POSIX file zipPath as alias
--set att to choose file
using terms from application "Mail"
tell application "Mail"
set m to make new outgoing message with properties {subject:"$subject_stub" & datestr, visible:true}
tell m
make new to recipient at end of to recipients with properties {address:"$target_address"}
end tell
tell content of m
make new attachment with properties {file name:att} at before first paragraph
end tell
(* Commented out so it doesn't auto-send the e-mail
tell m to send
*)
activate
end tell
end using terms from
"Done!"
EOT

Mirrored from fbartho.com.

applescript, tools, development, scripts

Previous post
Up