最近某人要代表学校批量发送邮件欢迎新生,而且有几个特殊的要求:
- 邮件必须每个人独立发一封,因为给每个人的邮件要正确的称呼这个人的名字。因此邮件必须批量发送,而不能够以 bcc 的形式一封邮件发给所有人。
- 邮件需要带上附件。
- 邮件没办法提供「退订」链接。这导致我们不能够使用 MailChimp,因为 MailChimp 根据法律要求邮件列表必须提供退订链接。
为此我想到了用 AppleScript 来控制 Mac 上的 Mail 来批量发送邮件。搜索一番后,写出如下的 AppleScript 来:
set theRecipients to {{name:"Cat Chen", email:"catchen@catchen.me"}, {name:"Roli Chen", email:"roli@chen.cat"}, {name:"Elle Chen", email:"elle@chen.cat"}} | |
set theAttachment to (choose file with prompt "Select file for attachment...") | |
tell application "Mail" | |
repeat with theRecipient in theRecipients | |
set theMessage to make new outgoing message with properties {visible:true, subject:"Email with File Attachment", content:"Hi " & name of theRecipient & "," & linefeed & linefeed & "Check out the attachment in this email!" & linefeed & linefeed} | |
tell theMessage | |
make new to recipient at end of to recipients with properties {name:name of theRecipient, address:email of theRecipient} | |
make new attachment at end of last character of content with properties ¬ | |
{file name:theAttachment} | |
end tell | |
delay 1 | |
send theMessage | |
end repeat | |
end tell |
在这个 AppleScript 里,我通过 theRecipients
提供一个姓名及邮件的列表,然后打开系统对话框选择一个用作附件的邮件,接着利用循环逐一发送邮件。代码里面最 tricky 的一行是 delay 1
,如果没有这一行代码附件会添加失败,但邮件文本会被发送出去。我也无法解释为什么会这样子,使用 delay 1
是我从网上搜索回来的解决方案,如果你知道为什么要这样做,请在评论告诉我。
最后,现在 AppleScript 的文档实在难找。例如说我想找 Mail 支持的所有 AppleScript 操作现在已经找不到了,Apple 网站上一些原有的 AppleScript 文档链接已经失效。现在能做的也就是看着别人过去留下的 AppleScript 自己慢慢摸索。如果你有更好的 AppleScript 文档,请在评论分享一下。