Advertisement

Terminal tip: easy email attachments

If you're looking to automate the sending of emails with attachments quickly and easily (and aren't too concerned with having some glamorous stationery), Terminal is once again your friend. It's possible with Mail.app and AppleScript, but there are a few pitfalls and, for most purposes, a simple shell command will do the trick:

(echo "This is the message body";uuencode Desktop/yourDoc.doc yourDoc.doc)|mail -s "Test attachment" someone@adomain.com

The magical command in this one is uuencode, which is used to encode and decode binary files and can be used on just about any file type. The two arguments in the command above define the name and location of the source file and the name the file should have when it's received. The parenthetical statement at the beginning combines the results of the echo and uuencode commands which are then piped (|) to the mail command. The mail command, having received the body text and attachment, is told to append a subject (-s "Subject") and send it to the address specified. If you wanted to send a longer text file – with line breaks, perhaps – as the body, you could save the text in an external file and replace the echo statement with cat myfile.txt.

By adding a little complexity you could make a shell script that takes arguments, making the automation a little more flexible. But TUAW reader Adam was wondering how to send a photo he'd taken automatically using AppleScript (triggered by a Mail Rule). So here's an AppleScript implementation that doesn't require opening Terminal or dealing with Mail.app scripting:

set msgBody to "This is the body of the message"
set msgSubj to "Message subject"
set mailDest to "someone@adomain.com"
do shell script "(echo '" & msgBody & "'; uuencode /Users/you/Desktop/pictosend.jpg pictosend.jpg) | mail -s '" & msgSubj & "' " & mailDest

Make sure you remove any line breaks from that last line. This obviously requires a predetermined image name, but that could be made a variable as well and used as part of a larger script. We hope this helps, Adam!