使用Javascript for Automation发送带附件的电子邮件

Ole*_*ann 6 macos scripting osx-yosemite javascript-automation

我想在OS X Yosemite中使用Javascript for Automation在Mail.app中创建一个新的电子邮件消息并将文件附加到电子邮件中.这是我的代码:

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"
Run Code Online (Sandbox Code Playgroud)

它工作正常,直到这一点.我看到一个新的消息窗口,其中正确填写了收件人,主题和正文.但我无法弄清楚如何在邮件中添加文件附件.Mail.app的脚本字典表明contents属性(一个实例RichText)可以包含附件,但我不知道如何添加附件.

我试过这个,但是我收到一个错误:

// This doesn't work.
attachment = Mail.Attachment({ fileName: "/Users/myname/Desktop/test.pdf" })
message.content.attachments = [ attachment ]
// Error: Can't convert types.
Run Code Online (Sandbox Code Playgroud)

我在网上找到了几个例子,说明如何做到这一点的AppleScript中,比如这一个:

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
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何将其转换为Javascript.

JMi*_*lTX 6

基于@tlehman 的上述答案,我发现他的解决方案非常有效,除了一件事:附件不成功。没有错误,没有消息,只是没有在消息中添加附件。解决方法是使用Path()方法。

这是他的解决方案+Path()方法,如果路径中有任何空格,则需要该方法:

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: Path("/Users/myname/Desktop/if the file has spaces in it test.pdf") })
message.attachments.push(attachment)
Run Code Online (Sandbox Code Playgroud)


tle*_*man 5

我找到了通过反复试验来做到这一点的方法,你需要使用message.attachments.push(attachment)而不是attachments = [...]

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)
Run Code Online (Sandbox Code Playgroud)