Copying files to the clipboard using applescript

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?


Solution 1:

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).

Solution 2:

You can do something like :

set f to {(POSIX file "/path/to/a/folder/a.png"), (POSIX file "/path/to/another/folder/b.png")}
tell application "Finder"
    try -- to delete any old temp folder
        delete folder "AS_mailCopy" of (path to temporary items)
    end try
    set tmp to make new folder at (path to temporary items) with properties {name:"AS_mailCopy"}
    duplicate f to tmp
    select files of tmp
    activate
    tell application "System Events" to keystroke "c" using command down
    delete tmp
end tell

Now your pasteboard contains multiple files (from various folders) that you can paste into your mail.