我想在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中执行此操作的示例,例如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
但我无法弄清楚如何将其转换为Javascript。
答案 0 :(得分: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)
答案 1 :(得分:4)
基于@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)