You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript技术实现:如何基于搜索或智能邮箱过滤Apple Mail邮件?

优化Apple Mail内容搜索的高效方案

兄弟,我太懂你这种用AppleScript遍历邮件慢到抓狂的感受了——逐个读取每封邮件内容的效率简直感人,慢100倍都算保守估计。下面给你两种靠谱的解决思路,其中第一种就是你想要的UI自动化调用内置搜索,第二种则是更稳定高效的原生API方案:

方案一:UI自动化调用Apple Mail内置搜索

这种方法模拟人工操作搜索框,直接利用Mail原生的快速搜索能力,处理速度会比你原来的循环快N倍。

代码示例

set searchQuery to "content:\"findtext\" dateReceived >= \"2024-01-01\"" -- 替换成你的搜索词和目标日期
set targetMailbox to mailbox "INBOX" of application "Mail"

-- 激活Mail并选中目标邮箱
tell application "Mail"
    activate
    set selected mailboxes to {targetMailbox}
end tell

-- 模拟UI操作调出搜索框并执行搜索
tell application "System Events"
    tell process "Mail"
        -- 按下Command+F打开搜索框
        keystroke "f" using command down
        delay 0.2 -- 给系统一点响应时间
        -- 输入搜索规则
        keystroke searchQuery
        -- 回车执行搜索
        keystroke return
        delay 0.5 -- 根据邮件数量调整延迟,确保搜索结果加载完成
    end tell
end tell

-- 处理搜索到的邮件
tell application "Mail"
    set foundMessages to selected messages of front message viewer
    repeat with aMessage in foundMessages
        set tContent to content of aMessage as rich text
        -- 这里替换成你要执行的操作
        log "正在处理邮件:" & subject of aMessage
    end repeat
end tell

注意事项

  • 要在系统设置>隐私与安全性>辅助功能里,允许运行脚本的程序(比如Script Editor)控制你的电脑,否则System Events无法操作UI
  • 延迟时间可以根据你的邮件总量调整,避免搜索结果还没加载完就开始处理
  • 搜索查询的格式和Mail搜索栏的语法一致,比如content:"关键词"指定内容搜索,dateReceived >= "YYYY-MM-DD"指定日期范围

方案二:用AppleScript原生搜索API(更稳定高效)

其实Mail的AppleScript支持直接调用内置搜索功能,完全不需要依赖UI,速度和原生搜索一样快,还不会因为界面更新失效,比UI自动化更靠谱。

代码示例

set searchQuery to "content:\"findtext\" AND dateReceived >= \"2024-01-01\""
set targetMailbox to mailbox "INBOX" of application "Mail"

tell application "Mail"
    -- 直接搜索指定邮箱,返回符合条件的邮件列表
    set foundMessages to search targetMailbox for searchQuery
    repeat with aMessage in foundMessages
        set tContent to content of aMessage as rich text
        -- 替换成你的业务逻辑
        log "找到匹配邮件:" & subject of aMessage
    end repeat
end tell

优势说明

  • 完全基于原生API,不受界面变化影响,稳定性拉满
  • 搜索效率和Mail内置搜索一致,比你原来的循环快几十上百倍
  • 搜索语法和平时在Mail里用的规则完全相同,上手零成本

内容的提问来源于stack exchange,提问作者Steve Gon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:27:33