Gmail 智能写作与邮件自动化
High Contrast
Dark Mode
Light Mode
Sepia
Forest
2 min read316 words

Gmail 智能写作与邮件自动化

每天处理邮件平均花费 2.5 小时——通过 Claude + Gmail API 自动化,可以压缩到 40 分钟。

Gmail + Claude 集成架构

graph LR GMAIL[Gmail] --> TRIGGER[触发条件] TRIGGER --> T1[新邮件到达] TRIGGER --> T2[定时批处理] TRIGGER --> T3[手动触发] T1 --> CLAUDE[Claude API] T2 --> CLAUDE T3 --> CLAUDE CLAUDE --> ACTION[自动行动] ACTION --> A1[分类打标签] ACTION --> A2[起草回复] ACTION --> A3[提取行动项] ACTION --> A4[摘要通知] style CLAUDE fill:#c8e6c9,stroke:#388e3c,stroke-width:2px style ACTION fill:#e3f2fd,stroke:#1565c0,stroke-width:2px

Gmail + Claude API 自动化

"""
Gmail + Claude API 邮件智能处理系统
(演示版:使用模拟 Gmail 数据,实际需要 Google OAuth)
"""
import anthropic
from dataclasses import dataclass, field
from enum import Enum
class EmailCategory(Enum):
ACTION_REQUIRED = "需要行动"
FYI = "仅供知悉"
NEWSLETTER = "通讯/资讯"
CUSTOMER = "客户邮件"
INTERNAL = "内部沟通"
SPAM = "垃圾邮件"
@dataclass
class Email:
id: str
sender: str
sender_name: str
subject: str
body: str
received_at: str
is_read: bool = False
labels: list[str] = field(default_factory=list)
@dataclass
class EmailAnalysis:
email_id: str
category: EmailCategory
priority: str          # urgent / high / normal / low
summary: str
action_items: list[str]
suggested_reply: str
reply_needed: bool
estimated_reply_time: str
class GmailClaudeProcessor:
"""Gmail + Claude 邮件智能处理器"""
SYSTEM_PROMPT = """You are an expert email assistant. Analyze emails and provide:
1. Category classification
2. Priority assessment
3. Concise summary (2-3 sentences max)
4. Specific action items (if any)
5. Draft reply (if reply is needed)
Always be concise and action-oriented. Output in JSON format."""
def __init__(self, api_key: str = "demo"):
self.api_key = api_key
# 实际使用时: self.client = anthropic.Anthropic(api_key=api_key)
def analyze_email(self, email: Email, user_context: str = "") -> EmailAnalysis:
"""分析单封邮件(演示版使用模拟分析)"""
# 实际调用示例:
# response = self.client.messages.create(
#     model="claude-sonnet-4-5-20251001",
#     max_tokens=1024,
#     system=self.SYSTEM_PROMPT,
#     messages=[{
#         "role": "user",
#         "content": f"Analyze this email:\n\nFrom: {email.sender_name}\nSubject: {email.subject}\n\n{email.body}\n\nUser context: {user_context}"
#     }]
# )
# 演示:基于关键词的简单分类
body_lower = email.body.lower()
subject_lower = email.subject.lower()
# 优先级判断
urgent_signals = ["urgent", "asap", "immediately", "deadline today", "紧急", "今天必须"]
priority = "urgent" if any(s in body_lower + subject_lower for s in urgent_signals) else "normal"
# 类别判断
if any(w in email.sender for w in ["@newsletter", "noreply@", "no-reply@"]):
category = EmailCategory.NEWSLETTER
elif any(w in subject_lower for w in ["invoice", "payment", "order", "purchase"]):
category = EmailCategory.CUSTOMER
elif any(w in email.sender for w in ["@company.com", "@internal"]):
category = EmailCategory.INTERNAL
elif any(w in subject_lower for w in ["action required", "please review", "approval needed"]):
category = EmailCategory.ACTION_REQUIRED
else:
category = EmailCategory.FYI
# 是否需要回复
reply_needed = category in (EmailCategory.ACTION_REQUIRED, EmailCategory.CUSTOMER)
return EmailAnalysis(
email_id=email.id,
category=category,
priority=priority,
summary=f"来自 {email.sender_name} 的邮件,主题:{email.subject}",
action_items=["查看邮件内容", "在 24 小时内回复"] if reply_needed else [],
suggested_reply=self._draft_reply(email) if reply_needed else "",
reply_needed=reply_needed,
estimated_reply_time="5 分钟" if reply_needed else "无需回复",
)
def _draft_reply(self, email: Email) -> str:
"""生成回复草稿"""
return f"""Hi {email.sender_name.split()[0]},
Thank you for reaching out. I've reviewed your message regarding "{email.subject}".
[在这里填写具体回复内容]
Please let me know if you need any clarification.
Best regards,
[Your Name]"""
def batch_process(self, emails: list[Email]) -> dict:
"""批量处理邮件"""
results = []
stats = {
"total": len(emails),
"urgent": 0,
"reply_needed": 0,
"by_category": {},
}
for email in emails:
analysis = self.analyze_email(email)
results.append(analysis)
if analysis.priority == "urgent":
stats["urgent"] += 1
if analysis.reply_needed:
stats["reply_needed"] += 1
cat = analysis.category.value
stats["by_category"][cat] = stats["by_category"].get(cat, 0) + 1
return {"analyses": results, "stats": stats}
class GmailFilter:
"""高级邮件过滤与自动标记规则"""
RULES = [
{
"name": "VIP 客户",
"conditions": ["from:@bigclient.com", "subject:urgent"],
"actions": ["label:VIP", "star", "forward:boss@company.com"],
},
{
"name": "自动归档通讯",
"conditions": ["from:newsletter", "from:noreply"],
"actions": ["label:Newsletter", "archive", "mark_read"],
},
{
"name": "发票处理",
"conditions": ["subject:invoice", "subject:payment", "has:attachment"],
"actions": ["label:Finance", "forward:finance@company.com"],
},
]
@classmethod
def print_rules(cls):
print("=== Gmail 自动化过滤规则 ===\n")
for rule in cls.RULES:
print(f"规则: {rule['name']}")
print(f"  条件: {', '.join(rule['conditions'])}")
print(f"  动作: {', '.join(rule['actions'])}\n")
# 演示
sample_emails = [
Email("001", "client@bigco.com", "David Chen",
"URGENT: Contract review needed by EOD",
"Hi, we need your review on the attached contract. This is time-sensitive as we need to sign by tomorrow.",
"2026-03-23 09:00"),
Email("002", "newsletter@techdigest.com", "Tech Digest",
"Weekly AI News - Top 10 Stories",
"This week in AI: Claude 4 release, GPT-5 rumors...",
"2026-03-23 08:00"),
Email("003", "teammate@company.com", "Sarah",
"Team lunch tomorrow?",
"Hey, are you joining the team lunch at noon tomorrow?",
"2026-03-23 10:00"),
]
processor = GmailClaudeProcessor()
result = processor.batch_process(sample_emails)
print("=== Gmail 邮件批量分析 ===\n")
print(f"总计: {result['stats']['total']} 封  |  "
f"紧急: {result['stats']['urgent']} 封  |  "
f"需回复: {result['stats']['reply_needed']} 封\n")
for analysis in result["analyses"]:
email = next(e for e in sample_emails if e.id == analysis.email_id)
print(f"[{analysis.priority.upper()}] {email.subject}")
print(f"  类别: {analysis.category.value}  预计处理: {analysis.estimated_reply_time}")
if analysis.reply_needed:
print(f"  📝 需要回复")
print()
GmailFilter.print_rules()

邮件提示词速查

场景 提示词模板
回复客户投诉 以专业温和的语气回复这封投诉邮件,道歉并给出解决方案:[粘贴邮件]
跟进未回复 写一封友好但明确的跟进邮件,上次邮件发于X天前,主题是[主题]
会议邀请 起草一封邀请[姓名]参加[主题]会议的邮件,时间[日期],目的是[目的]
委婉拒绝 帮我写一封婉拒[请求]的邮件,理由是[理由],保持良好关系
摘要长邮件链 摘要这封邮件链的关键决策和行动项:[粘贴邮件链]

行动清单

下一节02-Google-Docs与Sheets-AI辅助 — 文档写作和表格分析的 AI 增强工作流。