使用 Javascript 发送带附件的电子邮件以实现自动化

Send email with attachment using Javascript for Automation

我想在 OS X Yosemite 中将 Javascript 用于自动化,以在 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"

到这里为止一切正常。我看到一封新邮件 window,其中正确填写了收件人、主题和正文文本。但我不知道如何向邮件添加文件附件。 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。

我通过反复试验找到了一种方法,您需要使用 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)

基于@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)