PAYATHON 2026

AppleScript 为 Apple Mail 创建子文件夹时出现异常名称

数据小陈

结论

不要把 parentFolderName & "/" & subfolderName 传给新邮箱的 name。name 表示邮箱显示名,不用来表示层级路径。创建子文件夹时,应把父 mailbox 作为 make new mailbox 的目标位置,name 里只传子文件夹名。

原因

Apple Mail 的 AppleScript 接口通过 mailbox 对象的容器关系表示层级。make new mailbox with properties {name:...} 只使用传入的 name 创建邮箱名称,不会把斜杠 / 当成路径分隔符。所以传入 "Customers/testfolder" 得到的是名为 Customers/testfolder 的邮箱,而不是 Customers 下的 testfolder。

正确写法

父文件夹位于 Exchange 账户根层时:

tell application "Mail"
    set theAccount to account "Exchange"
    set parentMailbox to first mailbox of theAccount whose name is parentFolderName
    make new mailbox at parentMailbox with properties {name:subfolderName}
end tell

完整脚本可改成:

on run argv
    if (count of argv) is not 2 then
        error "Usage: osascript create_mail_subfolder.applescript <parent-folder-name> <subfolder-name>"
    end if

    set parentFolderName to item 1 of argv
    set subfolderName to item 2 of argv

    tell application "Mail"
        set theAccount to account "Exchange"
        set parentMailbox to first mailbox of theAccount whose name is parentFolderName

        if exists mailbox subfolderName of parentMailbox then
            error "Subfolder already exists: " & subfolderName
        end if

        make new mailbox at parentMailbox with properties {name:subfolderName}
    end tell
end run

运行方式不变:

% osascript create_mail_subfolder.applescript "Customers" "testfolder"

如果父文件夹不在账户根层,就需要逐层找到父 mailbox,例如:

set grandParent to mailbox "GrandParent" of theAccount
set parentMailbox to mailbox parentFolderName of grandParent

再对 parentMailbox 执行创建操作。

注意事项

  • 账户名要填 Mail 中显示的 Exchange 账户名,不能填邮箱地址。
  • name 里不要放 / 或其他路径拼接符;层级由 at parentMailbox 或容器对象决定。
  • 创建前先检查 exists mailbox subfolderName of parentMailbox,避免重复创建。
  • Exchange 同步可能有延迟,脚本返回成功不代表服务器端马上就能看到。
  • 如果找不到父文件夹,先确认它在 Mail 里的实际层级,再用完整的 mailbox ... of ... 路径引用。 备注:内容仅供参考。