Copying files to the clipboard using applescript

applescriptcommand linecopy/paste

Often I find myself at the command line wanting to copy files to the clipboard, so that I can paste them as attachments in Mail. If I have an image file, image1.png, I can accomplish this with

osascript -e 'tell app "Finder" to set the clipboard to ( POSIX file "image1.png" )'

If I execute the above command and then open a new message in Mail and press command V, the image file is pasted as an attachment. Note that pbcopy is apparently not a solution here, because this would copy the contents of the file and result in junk when pasted with command V.

My question is how can I do the same thing with multiple files? Suppose I want to paste both image1.png and image2.png. This is trivial from Finder (select them both, command C, then switch to Mail and command V; voila, both files show up as attachments)… but how can I do this from the command line?

Best Answer

This isn't quite perfect for what you want, but I think it might get you closer. Quicksilver has a command line tool. When installed, you can pipe files from the command line to Quicksilver app, and from there send them as attachments in Mail.

To install Quicksilver command line tool, activate Quicksilver. Then navigate to Quicksilver > Preferences to open preferences window. Click on Preferences on top right of window. On the left, click on Command Line Tool and install.

In Terminal, you'll be able to type

qs path/to/file1 path/to/file2 path/to/file3 path/to/file4

Pressing enter will send those files to Quicksilver's first pane. Press tab to move to the action pane and choose the Mail/New Email With Attachment action. Press enter, and a new email with your selected files attached should appear.

Note that you will also have to install the Mail and Command Line plugins in Quicksilver (Quicksilver > Preferences > Plug Ins).