6

我想在 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"

到目前为止,它工作正常。我看到一个新的消息窗口,其中正确填写了收件人、主题和正文。但我不知道如何在消息中添加文件附件。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.

我在网上找到了几个如何在 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

但我不知道如何将其转换为 Javascript。

4

2 回答 2

6

我想出了一种通过反复试验来做到这一点的方法,你需要使用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)
于 2015-01-02T18:18:45.677 回答
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)

于 2018-08-24T20:58:25.137 回答