Python自动化:调用企业微信API高效推送邮件通知
1. 为什么需要企业微信邮件自动化每天手动发送运营报告的日子我受够了。作为团队的技术负责人曾经每周都要花2小时整理数据、写邮件、检查收件人列表。直到发现企业微信API能实现全自动化现在整个过程只需30秒准确率还更高。企业微信的邮件API功能比你想象的强大。它不仅能发送普通文本邮件还支持HTML格式、附件上传、群发管理等功能。我们团队用它实现了每日凌晨自动发送前一日销售数据系统异常实时邮件报警周报自动汇总分发客户生日祝福自动触发最让我惊喜的是API调用成功率高达99.9%比人工操作更可靠。上周服务器宕机时报警邮件比监控系统还早3分钟到达运维人员邮箱。2. 准备工作获取API通行证2.1 创建企业微信应用登录企业微信管理后台在应用管理点击创建应用。建议命名规范如邮件自动化_部门_用途我们用的是MailBot_Tech_DailyReport。创建完成后会看到三个关键参数AgentId应用的身份证号如1000002CorpId企业的统一标识Secret相当于应用密码务必保管好我犯过的错第一次把Secret保存在代码里直接提交到了GitHub结果被安全团队警告。现在都用环境变量存储# 在Linux/macOS的~/.bashrc添加 export WX_CORP_IDyour_corp_id export WX_APP_SECRETyour_app_secret2.2 配置邮件服务器进入邮件-邮件服务器配置需要准备SMTP服务器地址如smtp.exmail.qq.com端口号通常465或587管理员邮箱需开通SMTP服务授权码不是邮箱密码测试时遇到过坑腾讯企业邮箱要求用授权码而非密码这个设置藏得很深在邮箱设置-账户-安全设置里。3. Python实战从零编写发送脚本3.1 获取AccessTokenAccessToken是API调用的门票有效期2小时。建议用这个缓存方案import requests import time from os import environ TOKEN_CACHE { token: None, expires_at: 0 } def get_access_token(): if TOKEN_CACHE[token] and time.time() TOKEN_CACHE[expires_at]: return TOKEN_CACHE[token] url fhttps://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid{environ[WX_CORP_ID]}corpsecret{environ[WX_APP_SECRET]} resp requests.get(url).json() TOKEN_CACHE.update({ token: resp[access_token], expires_at: time.time() resp[expires_in] - 300 # 提前5分钟刷新 }) return TOKEN_CACHE[token]3.2 发送带附件的邮件这是我们正在用的增强版发送函数def send_email_with_attachment(subject, content, to_users, filesNone): token get_access_token() url https://qyapi.weixin.qq.com/cgi-bin/message/send payload { touser: to_users, msgtype: file, agentid: environ.get(WX_AGENT_ID), file: { media_id: upload_file(token, files[0]) if files else }, text: { content: f{subject}\n\n{content} }, safe: 0 } response requests.post( url, params{access_token: token}, jsonpayload ) return response.json() def upload_file(token, filepath): url fhttps://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token{token}typefile with open(filepath, rb) as f: return requests.post(url, files{media: f}).json()[media_id]4. 高级技巧与避坑指南4.1 收件人智能处理我们开发了动态收件人系统def get_recipients_by_department(dept_id): url fhttps://qyapi.weixin.qq.com/cgi-bin/user/list?access_token{get_access_token()}department_id{dept_id} users requests.get(url).json().get(userlist, []) return |.join(user[userid] for user in users) # 发送给技术部全体 tech_users get_recipients_by_department(2) send_email_with_attachment(技术周报, weekly_report, tech_users)4.2 错误处理与重试机制企业微信API偶尔会返回40001token过期错误这是我们的解决方案def safe_send_email(max_retry3, **kwargs): for i in range(max_retry): try: result send_email_with_attachment(**kwargs) if result.get(errcode) 0: return True if result.get(errcode) 40001: TOKEN_CACHE[token] None # 强制刷新token except Exception as e: print(fAttempt {i1} failed: {str(e)}) time.sleep(2 ** i) # 指数退避 return False5. 自动化实战定时发送运营报表用APScheduler实现定时任务from apscheduler.schedulers.blocking import BlockingScheduler def generate_daily_report(): # 这里连接数据库生成报告 return 昨日UV: 15243\nPV: 87421\n转化率: 3.2% scheduler BlockingScheduler() scheduler.scheduled_job(cron, hour8, minute30) def morning_report(): report generate_daily_report() send_email_with_attachment( subject每日运营简报, contentreport, to_usersget_recipients_by_department(3), files[/reports/daily_stats.pdf] ) scheduler.start()我在服务器部署时发现直接用nohup运行会丢失日志后来改用supervisor管理进程[program:wx_mail_bot] commandpython /opt/scripts/mail_bot.py autostarttrue autorestarttrue stderr_logfile/var/log/wx_mail_err.log stdout_logfile/var/log/wx_mail_out.log
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2492711.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!