I would like use Javascript for Automation in OS X Yosemite to create a new email message in Mail.app and attach a file to the email. This is my code:
Mail = Application('com.apple.Mail')
message = Mail.OutgoingMessage().make()
message.visible = true
message.toRecipients.push(Mail.Recipient({ address: "[email protected]" }))
message.subject = "Test subject"
message.content = "Lorem ipsum dolor sit"
It works fine until this point. I see a new message window with the recipient, subject, and body text correctly filled in. But I can’t figure out how to add a file attachment to the message. The scripting dictionary for Mail.app indicates that the contents
property (an instance of RichText
) can contain attachments, but I don’t know how to add one.
I tried this but I get an error:
// This doesn't work.
attachment = Mail.Attachment({ fileName: "/Users/myname/Desktop/test.pdf" })
message.content.attachments = [ attachment ]
// Error: Can't convert types.
I found several examples on the web how to do this in AppleScript, for example this one:
tell application "Mail"
...
set theAttachmentFile to "Macintosh HD:Users:moligaloo:Downloads:attachment.pdf"
set msg to make new outgoing message with properties {subject: theSubject, content: theContent, visible:true}
tell msg to make new attachment with properties {file name:theAttachmentFile as alias}
end tell
But I can’t figure out how to convert this to Javascript.
Mail.make({new:k.outgoingMessage, at:message.attachments, withProperties:{visible:true,subject:"Test",content:"Foo"}})
, because that's how Apple events actually work; i.e. RPC + simple relational queries. But the AS team insists on lying to users of languages such as JavaScript and Objective-C, so you have to wade through this faux-OOP crap that pretends (badly) that you're manipulating a localArray
object instead of describing a one-to-many relationship in the remote process's object graph. #HeadDesk – Randi