AI邮件自动化2026:GPT-4 + Gmail API实现智能收件箱管理
利用AI自动分类、摘要和起草邮件回复
AI邮件自动化2026:GPT-4 + Gmail API实现智能收件箱管理
利用AI自动分类、摘要和起草邮件回复
使用GPT-4和Gmail API构建AI邮件自动化系统。涵盖邮件分类、优先级评分、自动草稿生成和路由,每周节省数小时的收件箱管理时间。
AI邮件自动化2026:GPT-4 + Gmail API实现智能收件箱管理
利用AI自动分类、回复和管理您的邮件收件箱。
可自动化的功能
设置:Gmail API
bash
pip install google-auth google-auth-oauthlib google-api-python-client openai
python
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials
import base64
import osSCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def get_gmail_service():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as f:
f.write(creds.to_json())
return build('gmail', 'v1', credentials=creds)
读取邮件
python
from openai import OpenAIopenai = OpenAI()
service = get_gmail_service()
def get_unread_emails(max_results: int = 10):
results = service.users().messages().list(
userId='me',
labelIds=['INBOX', 'UNREAD'],
maxResults=max_results
).execute()
emails = []
for msg in results.get('messages', []):
email = service.users().messages().get(userId='me', id=msg['id'], format='full').execute()
headers = {h['name']: h['value'] for h in email['payload']['headers']}
body = ''
if 'parts' in email['payload']:
for part in email['payload']['parts']:
if part['mimeType'] == 'text/plain' and 'data' in part['body']:
body = base64.urlsafe_b64decode(part['body']['data']).decode()
break
emails.append({
'id': msg['id'],
'from': headers.get('From', ''),
'subject': headers.get('Subject', ''),
'body': body[:2000] # 截断以符合token限制
})
return emails
AI邮件分类
python
import jsondef classify_email(email: dict) -> dict:
r = openai.chat.completions.create(
model='gpt-4o-mini',
messages=[{
'role': 'user',
'content': f'Classify this email. Return JSON with fields: '
f'category (support/sales/spam/internal/urgent/newsletter), '
f'priority (high/medium/low), '
f'sentiment (positive/neutral/negative), '
f'summary (one sentence).\n\n'
f'From: {email["from"]}\n'
f'Subject: {email["subject"]}\n'
f'Body: {email["body"]}'
}],
response_format={'type': 'json_object'}
)
return json.loads(r.choices[0].message.content)
处理所有未读邮件
emails = get_unread_emails(20)
for email in emails:
classification = classify_email(email)
print(f'{email["subject"]}: {classification["category"]} ({classification["priority"]})')
print(f' 摘要: {classification["summary"]}')
自动生成回复草稿
python
def generate_reply(email: dict, context: str = '') -> str:
r = openai.chat.completions.create(
model='gpt-4o',
messages=[{
'role': 'system',
'content': 'You are an professional email assistant. '
'Write clear, concise, professional email replies. '
'Match the tone of the original email.'
}, {
'role': 'user',
'content': f'Write a reply to this email.\n\n'
f'Original email:\n'
f'From: {email["from"]}\n'
f'Subject: {email["subject"]}\n'
f'Body: {email["body"]}\n\n'
f'Context/instructions: {context or "Be helpful and professional."}'
}]
)
return r.choices[0].message.contentdef save_draft(service, email_id: str, reply_text: str):
original = service.users().messages().get(userId='me', id=email_id, format='full').execute()
headers = {h['name']: h['value'] for h in original['payload']['headers']}
import email.mime.text
msg = email.mime.text.MIMEText(reply_text)
msg['To'] = headers.get('From', '')
msg['Subject'] = 'Re: ' + headers.get('Subject', '')
msg['In-Reply-To'] = headers.get('Message-Id', '')
raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
service.users().drafts().create(
userId='me',
body={'message': {'raw': raw, 'threadId': original['threadId']}}
).execute()
结论
AI邮件自动化为知识工作者每周节省数小时。从分类开始,然后为高量请求类型添加自动草稿生成。在生产环境中发送前,务必审查AI生成的草稿。
相关工具
相关教程
通过AI驱动的代码审查,自动发现拉取请求中的错误和安全问题
使用 Make (Integromat) 进行 AI 驱动自动化工作流的分步指南
使用 LiteLLM 构建 AI 驱动 API 工作流的分步指南
使用 Replicate 实现 AI 驱动 API 工作流的分步指南
AutoML与AI助手如何让数据科学大众化
使用 Modal 实现 AI 驱动的基础设施工作流的分步指南