macOS与AppleScript问题:邮件附件存指定文件夹并添加标签失败
AppleScript邮件规则脚本故障排查与修复
核心问题分析
- 延迟语句位置错误:
delay 10放在邮件规则处理函数外部,规则触发时不会执行,无法确保邮件附件下载完成。 - 附件保存方式错误:使用Finder的
make new file仅创建空文件,未实际写入附件内容。 - 路径处理不兼容:直接给Finder传递POSIX路径(
/Users/...)可能导致识别失败,需转为HFS路径或别名。 - 标签格式错误:
tags属性要求传入列表类型,而非单个字符串。 - 硬编码用户名:脚本中的
username未替换为实际用户名,导致路径无效。 - 日志输出不可见:Mail规则内的
log语句默认不会显示在系统控制台,调试困难。
修复后的完整脚本
using terms from application "Mail" on perform mail action with messages theMessages for rule theRule -- 等待10秒确保邮件附件下载完成 delay 10 repeat with theMessage in theMessages tell application "Mail" -- 获取当前用户桌面路径,避免硬编码 set desktopPath to path to desktop folder as text set saveFolderName to "Aktuelles" set saveFolderPath to desktopPath & saveFolderName repeat with theAttachment in mail attachments of theMessage set attachmentName to name of theAttachment -- 可改为不区分大小写:attachmentName ends with ".pdf" or attachmentName ends with ".PDF" if attachmentName ends with ".pdf" then -- 检查并创建目标文件夹 tell application "Finder" if not (exists folder saveFolderPath) then make new folder at desktopPath with properties {name:saveFolderName} end if end tell -- 保存附件到目标文件夹(关键修复:使用Mail的save命令) set saveFilePath to saveFolderPath & ":" & attachmentName save theAttachment in file saveFilePath -- 设置文件标签与时间属性 tell application "Finder" set targetFile to file saveFilePath set tags of targetFile to {"Aktuell"} -- 标签需为列表格式 set creation date of targetFile to current date set modification date of targetFile to current date end tell end if end repeat end tell end repeat end perform mail action with messages end using terms from
额外调试建议
- 临时添加
display dialog "脚本已触发"到函数开头,确认规则是否正确触发脚本。 - 检查邮件规则的触发条件是否匹配(如收件人、主题过滤设置是否正确)。
- 确保Mail应用拥有完全磁盘访问权限:系统设置 > 隐私与安全性 > 完全磁盘访问权限 > 勾选Mail。
- 测试脚本时,可在AppleScript编辑器中手动选中测试邮件,点击「运行」按钮直接调试,查看控制台输出。
内容的提问来源于stack exchange,提问作者jubx
相关产品推荐
相关产品推荐

