)
PythonGLM大模型实战30分钟搭建个人邮件智能摘要系统附完整代码在信息爆炸的时代我们每天都要处理大量电子邮件但真正重要的信息往往被淹没在琐碎的日常邮件中。本文将带你用Python和GLM大模型快速构建一个智能邮件摘要系统自动提取邮件核心内容让你在30分钟内拥有一个高效的信息过滤工具。1. 系统架构与核心组件这个邮件摘要系统的核心设计遵循轻量、高效、安全三大原则主要包含以下功能模块邮件获取层通过IMAP协议连接邮箱服务器内容处理层使用GLM大模型分析邮件内容摘要生成层将处理结果转化为易读格式调度控制层管理整个系统的运行周期系统工作流程如下图所示[邮箱服务器] → [邮件获取] → [内容分析] → [摘要生成] → [结果输出]1.1 技术选型对比我们对比了几种常见的技术方案方案类型开发复杂度安全性处理能力适用场景基础IMAP★★☆★★☆50封/次个人使用OAuth2认证★★★★★★★200封/次团队协作服务化架构★★★★★★★★1000封/次企业级应用对于个人开发者和小团队我们推荐使用OAuth2认证方案它在安全性和开发复杂度之间取得了良好平衡。2. 环境准备与配置2.1 基础环境搭建首先确保你的开发环境已安装Python 3.8然后创建项目目录结构mkdir email-digest-system cd email-digest-system python -m venv venv source venv/bin/activate # Linux/Mac # venv\Scripts\activate # Windows安装所需依赖库pip install aiohttp python-dotenv jinja2 cryptography imaplib22.2 关键配置说明创建.env配置文件包含以下关键参数# 邮箱配置 EMAIL_HOSTimap.gmail.com EMAIL_PORT993 EMAIL_ADDRESSyour_emailgmail.com EMAIL_PASSWORDyour_app_password # GLM模型配置 GLM_API_KEYyour_glm_api_key GLM_MODELglm-4 # 系统参数 CHECK_INTERVAL_MINUTES30 MAX_EMAILS_PER_RUN20注意对于Gmail邮箱建议使用应用专用密码而非账户密码以提高安全性。3. 核心代码实现3.1 邮件获取模块我们使用Python的imaplib库实现邮件获取功能import imaplib from email.header import decode_header class EmailFetcher: def __init__(self): self.imap_server None def connect(self, host, port, username, password): try: self.imap_server imaplib.IMAP4_SSL(host, port) self.imap_server.login(username, password) return True except Exception as e: print(f连接失败: {e}) return False def fetch_recent_emails(self, days1): if not self.imap_server: return [] self.imap_server.select(INBOX) _, messages self.imap_server.search(None, f(SINCE {days} days ago)) return messages[0].split()3.2 GLM模型集成使用异步方式调用GLM API处理邮件内容import aiohttp async def summarize_with_glm(content, api_key, modelglm-4): headers {Authorization: fBearer {api_key}} payload { model: model, messages: [{ role: user, content: f请用中文总结以下邮件内容突出关键信息:\n{content} }] } async with aiohttp.ClientSession() as session: async with session.post( https://open.bigmodel.cn/api/paas/v4/chat/completions, jsonpayload, headersheaders ) as response: return await response.json()3.3 摘要生成器将处理结果转换为易读格式from datetime import datetime class DigestGenerator: staticmethod def generate_html(emails): return f html body h1邮件摘要 {datetime.now().strftime(%Y-%m-%d)}/h1 {.join(fdivh3{e[subject]}/h3p{e[summary]}/p/div for e in emails)} /body /html 4. 系统集成与优化4.1 主调度程序将各模块组合成完整的工作流import asyncio from email_fetcher import EmailFetcher from glm_client import summarize_with_glm from digest_generator import DigestGenerator class EmailDigestSystem: def __init__(self): self.fetcher EmailFetcher() async def run(self): if not self.fetcher.connect(...): return email_ids self.fetcher.fetch_recent_emails() summaries [] for eid in email_ids: content self.fetcher.get_email_content(eid) summary await summarize_with_glm(content, ...) summaries.append({ id: eid, content: content, summary: summary }) html DigestGenerator.generate_html(summaries) with open(digest.html, w) as f: f.write(html)4.2 性能优化技巧批量处理使用asyncio.gather同时处理多封邮件缓存机制避免重复处理已读邮件错误重试对失败的API调用实现指数退避重试资源限制控制单次处理的邮件数量# 批量处理示例 async def batch_summarize(contents): tasks [summarize_with_glm(c) for c in contents] return await asyncio.gather(*tasks, return_exceptionsTrue)5. 部署与使用5.1 本地运行直接执行主程序python main.py5.2 定时任务配置在Linux系统中可以使用cron设置定时任务# 每天上午9点运行 0 9 * * * /path/to/venv/bin/python /path/to/main.py5.3 Docker部署创建DockerfileFROM python:3.9-slim WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD [python, main.py]构建并运行容器docker build -t email-digest . docker run -d --env-file .env email-digest6. 安全最佳实践使用环境变量存储敏感信息定期轮换API密钥限制邮件访问权限启用SSL/TLS加密实施访问日志审计重要永远不要在代码中硬编码密码或API密钥务必使用环境变量或密钥管理服务。这套系统我已经在实际工作中使用了半年多最大的感受是每天节省了至少1小时的邮件处理时间。特别是在处理客户支持邮件时系统能快速识别关键问题让我能把精力集中在解决方案上而不是信息筛选上。