本文目录导读:

- 方法一:Python + smtplib(最常用)
- 方法二:带HTML格式的日报
- 方法三:自动化定时发送(配合计划任务)
- 方法四:使用第三方服务
- 实战模板:带数据报告的高级版
- 邮箱配置注意事项
- 安全建议
- 部署建议
- 常见问题解决
我来分享几种自动发送日报邮件的方法,从简单到复杂。
Python + smtplib(最常用)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime
def send_daily_report():
# 邮件配置
smtp_server = "smtp.qq.com" # 使用QQ邮箱为例
smtp_port = 587 # TLS端口
sender_email = "your_email@qq.com"
sender_password = "your_authorization_code" # 邮箱授权码,不是登录密码
receiver_email = "boss@company.com"
# 构建邮件内容
today = datetime.now().strftime("%Y-%m-%d")
# 日报内容(可以从文件读取或动态生成)
report_content = f"""
日期:{today}
今日工作内容:
1. 完成了项目A的需求分析
2. 修复了3个Bug
3. 参加了团队会议
明日计划:
1. 继续开发功能B
2. 代码review
3. 准备周三的演示
遇到的问题:
暂无重大问题
"""
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = Header(f"日报 - {today}", 'utf-8')
# 添加正文
msg.attach(MIMEText(report_content, 'plain', 'utf-8'))
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 启用TLS加密
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
print("日报发送成功!")
except Exception as e:
print(f"发送失败:{e}")
# 执行发送
send_daily_report()
带HTML格式的日报
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
def send_html_daily_report():
# 邮件配置
smtp_server = "smtp.qq.com"
smtp_port = 587
sender_email = "your_email@qq.com"
sender_password = "your_authorization_code"
receiver_email = "boss@company.com"
today = datetime.now().strftime("%Y-%m-%d")
# HTML格式的日报
html_content = f"""
<html>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2 style="color: #333;">日报 - {today}</h2>
<h3 style="color: #0066cc;">📋 今日工作完成</h3>
<ul>
<li>✅ 完成了项目A的需求分析</li>
<li>✅ 修复了3个Bug(BUG-123, BUG-456, BUG-789)</li>
<li>✅ 参加了团队会议</li>
<li>✅ 编写了单元测试</li>
</ul>
<h3 style="color: #0066cc;">📅 明日计划</h3>
<ul>
<li>🔄 继续开发功能B</li>
<li>🔄 代码review</li>
<li>🔄 准备周三的演示</li>
</ul>
<h3 style="color: #ff6600;">⚠️ 遇到的问题</h3>
<ul>
<li>暂无重大问题</li>
</ul>
<hr>
<p style="color: #999; font-size: 12px;">此邮件由系统自动发送</p>
</body>
</html>
"""
msg = MIMEMultipart('alternative')
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = f"日报 - {today}"
# 添加HTML内容
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
print("HTML格式日报发送成功!")
except Exception as e:
print(f"发送失败:{e}")
send_html_daily_report()
自动化定时发送(配合计划任务)
Windows:任务计划程序
@echo off :: 创建批处理文件 run_daily_report.bat cd /d C:\path\to\your\script python daily_report.py
Linux/Mac:crontab
# 编辑crontab crontab -e # 每天下午5:30发送日报 30 17 * * * /usr/bin/python3 /path/to/daily_report.py # 工作日(周一至周五)下午5:30发送 30 17 * * 1-5 /usr/bin/python3 /path/to/daily_report.py
Linux/Mac:systemd timer(较新的方式)
# /etc/systemd/system/daily-report.service [Unit] Description=Daily Report Service [Service] Type=oneshot ExecStart=/usr/bin/python3 /path/to/daily_report.py # /etc/systemd/system/daily-report.timer [Unit] Description=Run daily report at 17:30 [Timer] OnCalendar=Mon-Fri *-*-* 17:30:00 Persistent=true [Install] WantedBy=timers.target
使用第三方服务
GitHub Actions(免费)
# .github/workflows/daily-report.yml
name: Daily Report
on:
schedule:
- cron: '30 9 * * 1-5' # UTC时间9:30 = 北京时间17:30
jobs:
send-report:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run report script
run: python daily_report.py
env:
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
阿里云函数计算
# 云函数代码
import json
import smtplib
from email.mime.text import MIMEText
def handler(event, context):
# 发送日报逻辑
send_daily_report()
return {
"statusCode": 200,
"body": json.dumps("Report sent successfully")
}
实战模板:带数据报告的高级版
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime
import os
class DailyReport:
def __init__(self, config):
self.smtp_server = config['smtp_server']
self.smtp_port = config['smtp_port']
self.sender = config['sender']
self.password = config['password']
self.receivers = config['receivers']
self.cc_receivers = config.get('cc_receivers', [])
def get_data(self):
"""获取日报数据 - 可以从数据库、API或文件读取"""
today = datetime.now().strftime("%Y-%m-%d")
# 示例数据,实际使用时替换为真实数据源
data = {
'date': today,
'completed_tasks': [
'完成需求文档修改',
'修复3个线上Bug',
'参加代码review会议'
],
'planned_tasks': [
'开发新功能模块',
'编写单元测试'
],
'issues': [
'数据库性能问题已修复'
],
'metrics': {
'代码提交': 5,
'Bug修复': 3,
'文档更新': 2
}
}
return data
def generate_html(self, data):
"""生成HTML格式的日报"""
tasks_html = ''.join([f'<li>✅ {task}</li>' for task in data['completed_tasks']])
plans_html = ''.join([f'<li>🔄 {plan}</li>' for plan in data['planned_tasks']])
issues_html = ''.join([f'<li>⚠️ {issue}</li>' for issue in data['issues']])
metrics_html = ''
for key, value in data['metrics'].items():
metrics_html += f'<tr><td>{key}</td><td style="text-align:center">{value}</td></tr>'
html = f"""
<html>
<head>
<style>
body {{ font-family: 'Microsoft YaHei', Arial, sans-serif; padding: 20px; background: #f5f5f5; }}
.container {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; padding: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
h2 {{ color: #333; border-bottom: 2px solid #0066cc; padding-bottom: 10px; }}
.section {{ margin: 20px 0; }}
.section-title {{ color: #0066cc; font-weight: bold; margin-bottom: 10px; }}
ul {{ padding-left: 20px; }}
li {{ margin: 8px 0; }}
table {{ width: 100%; border-collapse: collapse; margin: 10px 0; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background-color: #f2f2f2; }}
.footer {{ margin-top: 30px; color: #999; font-size: 12px; text-align: center; }}
</style>
</head>
<body>
<div class="container">
<h2>📊 工作日报告 - {data['date']}</h2>
<div class="section">
<div class="section-title">📋 今日完成</div>
<ul>{tasks_html}</ul>
</div>
<div class="section">
<div class="section-title">📅 明日计划</div>
<ul>{plans_html}</ul>
</div>
<div class="section">
<div class="section-title">📈 工作统计</div>
<table>
<tr><th>指标</th><th>数值</th></tr>
{metrics_html}
</table>
</div>
<div class="section">
<div class="section-title">🚨 问题与风险</div>
<ul>{issues_html}</ul>
</div>
<div class="footer">
<p>此邮件由系统自动生成</p>
<p>如有问题请联系 IT 支持</p>
</div>
</div>
</body>
</html>
"""
return html
def send(self):
"""发送邮件"""
data = self.get_data()
html_content = self.generate_html(data)
msg = MIMEMultipart('alternative')
msg['From'] = self.sender
msg['To'] = ', '.join(self.receivers)
if self.cc_receivers:
msg['Cc'] = ', '.join(self.cc_receivers)
msg['Subject'] = f"日报 - {data['date']}"
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
all_recipients = self.receivers + self.cc_receivers
try:
server = smtplib.SMTP(self.smtp_server, self.smtp_port)
server.starttls()
server.login(self.sender, self.password)
server.sendmail(self.sender, all_recipients, msg.as_string())
server.quit()
print(f"日报发送成功!收件人:{', '.join(all_recipients)}")
except Exception as e:
print(f"发送失败:{e}")
# 使用示例
if __name__ == "__main__":
config = {
'smtp_server': 'smtp.qq.com',
'smtp_port': 587,
'sender': 'your_email@qq.com',
'password': 'your_authorization_code', # 邮箱授权码
'receivers': ['boss@company.com', 'manager@company.com'],
'cc_receivers': ['team_lead@company.com']
}
report = DailyReport(config)
report.send()
邮箱配置注意事项
常用邮箱SMTP配置
| 邮箱 | SMTP服务器 | 端口(TLS) | 授权码获取 |
|---|---|---|---|
| QQ邮箱 | smtp.qq.com | 587 | 设置→账户→POP3/SMTP服务 |
| 163邮箱 | smtp.163.com | 587 | 设置→POP3/SMTP/IMAP |
| Gmail | smtp.gmail.com | 587 | Google账户→安全性→应用密码 |
| 企业微信 | smtp.exmail.qq.com | 587 | 管理后台→邮箱→安全设置 |
| Outlook | smtp.office365.com | 587 | 账户安全→双重验证→应用密码 |
获取邮箱授权码的方法
以QQ邮箱为例:
- 登录QQ邮箱网页版
- 点击"设置"→"账户"
- 找到"POP3/SMTP服务"
- 点击"开启"(需要手机验证)
- 获取授权码(16位字母数字组合)
安全建议
-
不要硬编码密码:使用环境变量或配置文件
import os password = os.environ.get('EMAIL_PASSWORD') -
使用配置文件:
// config.json { "email": { "server": "smtp.qq.com", "port": 587, "sender": "your_email@qq.com", "password": "your_authorization_code" } } -
加密存储:使用加密工具如
cryptography库 -
使用密钥管理服务:如 AWS Secrets Manager、Azure Key Vault
部署建议
个人使用
- Windows:任务计划程序 + Python脚本
- Mac/Linux:crontab + Python脚本
- 可用性:依赖电脑开机
企业级
- 使用 CI/CD 工具(Jenkins、GitLab CI)
- 云函数(AWS Lambda、阿里云函数计算)
- 可用性:99.9%+
开源方案
- Apache Airflow
- Celery + Crontab
常见问题解决
-
端口被屏蔽:尝试使用465端口(SSL)
server = smtplib.SMTP_SSL(smtp_server, 465)
-
发送超时:增加超时时间
server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
-
附件乱码:正确编码文件名
part.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename))
需要更具体的帮助或想了解某个特定邮箱的配置细节,请告诉我!