Send email with attachment using Javascript for automation
I would like to use Automation Javascript 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: "abc@example.com" }))
message.subject = "Test subject"
message.content = "Lorem ipsum dolor sit"
It works great up to this point. I see a new message box with correctly filled in recipient, subject and body text. But I can't figure out how to add the file attachment to the post. The scripting dictionary for Mail.app indicates that the property contents
(instance RichText
) can contain attachments, but I don't know how to add it.
I tried this, but I get the 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 some examples on the internet how to do this in AppleScript, like 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.
source to share
I figured out a way to do it through trial and error, you need to use message.attachments.push(attachment)
insteadattachments = [...]
Mail = Application('com.apple.Mail')
message = Mail.OutgoingMessage().make()
message.visible = true
message.toRecipients.push(Mail.Recipient({ address: "foo.bar@example.com" }))
message.subject = "Testing JXA"
message.content = "Foo bar baz"
attachment = Mail.Attachment({ fileName: "/Users/myname/Desktop/test.pdf" })
message.attachments.push(attachment)
source to share