AI生成邮件发送脚本(带附件/HTML排版)与定时爬取网站→邮件通知(价格监控原型)
想象一下:每天早晨咖啡还没喝完,你的邮箱就自动收到了心仪商品的最新价格;重要报告准时带着专业排版的附件发送到客户手中——这一切不需要你手动操作。本文将用不到100行代码带你实现这两个自动化神器!
一、为什么我们需要自动化邮件系统?
在数字化时代,自动邮件通知已成为效率利器:
- 电商价格监控(立省30%购物预算)
- 系统异常实时报警(运维必备)
- 日报/周报自动发送(告别重复劳动)
- 注册验证码发送(用户触达核心)
传统痛点:手动发邮件耗时、易遗漏;邮件排版混乱;附件添加繁琐
我们的解决方案:
二、环境准备:3分钟快速搭建
# 安装核心库
pip install schedule requests beautifulsoup4 yagmail
schedule
:轻量级定时任务调度yagmail
:史上最简单的Python发邮件库beautifulsoup4
:HTML解析神器
三、AI生成邮件发送脚本(带附件/HTML排版)
3.1 基础文本邮件发送
import yagmail# 配置邮箱 (以QQ邮箱为例)
yag = yagmail.SMTP(user='your_email@qq.com',password='xxxxxxxxxx', # 授权码非登录密码!host='smtp.qq.com',port=465
)# 发送简单邮件
yag.send(to='recipient@example.com',subject='AI自动邮件测试',contents='你好,这是一封由Python自动发送的邮件!'
)
重要提示:各大邮箱获取授权码方式:
- QQ邮箱:设置 → 账户 → POP3/IMAP服务 → 生成授权码
- 163邮箱:设置 → POP3/SMTP/IMAP → 开启服务
3.2 发送HTML格式专业邮件
html_content = """
<!DOCTYPE html>
<html>
<head><style>.card {border: 1px solid #e0e0e0;border-radius: 8px;padding: 20px;font-family: Arial, sans-serif;}.header {color: #2c3e50;border-bottom: 2px solid #3498db;padding-bottom: 10px;}.highlight {background-color: #f9f9f9;padding: 15px;border-left: 4px solid #3498db;}</style>
</head>
<body><div class="card"><h1 class="header">每日数据报告</h1><p>尊敬的客户,以下是您关注的最新数据:</p><div class="highlight"><h3>核心指标</h3><ul><li>网站访问量:<strong>12,458</strong></li><li>转化率:<strong>8.7%</strong></li><li>异常事件:<span style="color:green">0</span></li></ul></div><p>本邮件由AI系统自动生成,请勿直接回复</p></div>
</body>
</html>
"""yag.send(to='recipient@example.com',subject='带HTML排版的专业邮件',contents=[html_content]
)
效果对比:
文本邮件 | HTML邮件 |
---|---|
单调的纯文本 | 企业级卡片式设计 |
无样式无色彩 | 支持CSS自定义样式 |
无法嵌入图表 | 可集成动态数据可视化 |
3.3 添加附件的进阶技巧
# 单个附件
yag.send(to='recipient@example.com',subject='重要文件请查收',contents='请查看附件中的季度报告',attachments='/path/to/report.pdf'
)# 多个附件 + HTML内容
attachments = ['/data/report.pdf','/data/sales.xlsx','/images/chart.png'
]yag.send(to=['person1@domain.com', 'person2@domain.com'], # 支持群发cc='manager@company.com', # 抄送功能subject='多附件邮件演示',contents=[html_content, '\n\n附件包含详细数据'],attachments=attachments
)
3.4 常见问题排雷指南
-
SSL连接错误:
# 增加SSL上下文配置 import ssl context = ssl.create_default_context()yag = yagmail.SMTP(user='your_email@qq.com',password='xxxxxxxxxx',host='smtp.qq.com',port=465,smtp_ssl=True,smtp_ssl_context=context )
-
大附件发送失败:
- Gmail限制25MB,QQ邮箱限制50MB
- 解决方案:使用云存储链接代替附件
contents = f"下载链接:https://cloud.com/report.pdf"
四、定时爬取网站→邮件通知(价格监控原型)
4.1 网页爬虫核心实现
import requests
from bs4 import BeautifulSoupdef monitor_price(url, css_selector):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'}try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status() # 检查HTTP错误soup = BeautifulSoup(response.text, 'html.parser')price_element = soup.select_one(css_selector)if not price_element:return None, "价格元素未找到"# 清洗价格数据price_text = price_element.text.strip()price = float(price_text.replace('¥', '').replace(',', ''))return price, "成功获取价格"except Exception as e:return None, f"爬取失败: {str(e)}"# 示例:监控京东MacBook价格
macbook_url = "https://item.jd.com/100043477122.html"
selector = ".price .plus-price span" # 通过浏览器检查元素获取
4.2 CSS选择器定位技巧
定位方式 | 示例 | 适用场景 |
---|---|---|
类选择器 | .product-price | 大多数电商网站 |
ID选择器 | #priceblock_ourprice | Amazon特色 |
属性选择器 | [data-price] | 动态加载页面 |
层级选择器 | div.price span.current | 复杂嵌套结构 |
调试技巧:在Chrome开发者工具中使用
$('css_selector')
实时测试
4.3 价格监控逻辑实现
import time
import scheduleTARGET_PRICE = 8999.0 # 目标价格阈值
CHECK_INTERVAL = 60 * 4 # 每4小时检查一次def price_check_job():current_price, status = monitor_price(macbook_url, selector)if current_price is None:print(f"[{time.ctime()}] 监控失败: {status}")returnprint(f"[{time.ctime()}] 当前价格: ¥{current_price:.2f}")# 价格低于阈值时触发邮件if current_price <= TARGET_PRICE:alert_msg = f"""<h2>价格警报!🚨</h2><p>MacBook Pro 14 价格已降至 <strong style="color:red">¥{current_price:.2f}</strong></p><p>立即购买:<a href="{macbook_url}">商品链接</a></p>"""yag.send(to='your_phone@139.com', # 短信邮箱提醒subject='【降价提醒】MacBook Pro 14',contents=alert_msg)print("价格警报已发送!")# 设置定时任务
schedule.every(CHECK_INTERVAL).seconds.do(price_check_job)# 保持脚本运行
while True:schedule.run_pending()time.sleep(1)
4.4 反爬虫策略应对方案
-
IP被封禁:
- 使用代理IP池(推荐快代理、芝麻代理)
proxies = {"http": "http://user:pass@10.10.1.10:3128"} response = requests.get(url, proxies=proxies)
-
验证码拦截:
- 降低请求频率(间隔>30秒)
- 使用Selenium模拟浏览器
from selenium import webdriver driver = webdriver.Chrome() driver.get(url) price = driver.find_element_by_css_selector(selector).text
-
动态加载数据:
- 使用Selenium等待元素加载
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ECelement = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)) )
五、项目升级:企业级解决方案
5.1 架构优化方案
5.2 添加数据库存储
import sqlite3
import datetimedef save_price_record(item_id, price):conn = sqlite3.connect('price_monitor.db')c = conn.cursor()# 创建表c.execute('''CREATE TABLE IF NOT EXISTS prices(id INTEGER PRIMARY KEY AUTOINCREMENT,item_id TEXT,price REAL,timestamp DATETIME)''')# 插入数据c.execute("INSERT INTO prices (item_id, price, timestamp) VALUES (?, ?, ?)",(item_id, price, datetime.datetime.now()))conn.commit()conn.close()# 在获取价格后调用
save_price_record("jd_100043477122", current_price)
5.3 多商品监控配置
// config.json
[{"name": "MacBook Pro 14","url": "https://item.jd.com/100043477122.html","selector": ".price .plus-price span","target_price": 8999.0},{"name": "iPhone 15 Pro","url": "https://www.apple.com/cn/shop/buy-iphone/iphone-15-pro","selector": ".rc-prices-fullprice","target_price": 7999.0}
]
5.4 价格趋势分析可视化
import matplotlib.pyplot as plt
import pandas as pd# 从数据库读取数据
conn = sqlite3.connect('price_monitor.db')
df = pd.read_sql_query("SELECT * FROM prices WHERE item_id='jd_100043477122'", conn)# 绘制价格曲线
plt.figure(figsize=(10, 6))
plt.plot(pd.to_datetime(df['timestamp']), df['price'], 'b-', marker='o')
plt.title('MacBook Pro 14 价格趋势')
plt.xlabel('日期')
plt.ylabel('价格 (¥)')
plt.grid(True)# 保存为图片并发送
chart_path = '/tmp/price_trend.png'
plt.savefig(chart_path)# 在邮件中包含趋势图
yag.send(to='your_email@example.com',subject='每周价格趋势报告',contents='<h1>最新价格走势分析</h1>',attachments=chart_path
)
六、部署到生产环境
6.1 Linux服务器后台运行
# 安装必要环境
sudo apt update
sudo apt install python3-pip chromium-chromedriver# 安装Python依赖
pip install -r requirements.txt# 使用nohup后台运行
nohup python monitor.py > monitor.log 2>&1 &# 查看日志
tail -f monitor.log
6.2 使用Systemd管理服务
# /etc/systemd/system/price-monitor.service
[Unit]
Description=Price Monitor Service
After=network.target[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/price-monitor
ExecStart=/usr/bin/python3 /home/ubuntu/price-monitor/monitor.py
Restart=always[Install]
WantedBy=multi-user.target
# 启动服务
sudo systemctl start price-monitor# 设置开机自启
sudo systemctl enable price-monitor# 查看状态
sudo systemctl status price-monitor
七、最佳实践与法律边界
合法爬虫的黄金法则
- 遵守robots.txt:检查目标网站是否允许爬取
- 限制请求频率:≥5秒/请求,避免造成服务器压力
- 尊重版权数据:不爬取明确禁止的商业数据
- 用户隐私保护:绝不收集用户个人信息
推荐公共API优先:
- 电商:Amazon Product API, 京东宙斯API
- 金融:Alpha Vantage, Yahoo Finance
- 社交媒体:Twitter API, Facebook Graph API
八、项目扩展方向
-
多协议通知集成
- 企业微信机器人
- Slack/Discord Webhook
- 手机Push通知(Bark服务)
-
智能比价系统
- 跨平台比价(京东/天猫/拼多多)
- 历史价格查询
- 降价预测模型
-
云函数部署
# 腾讯云函数示例 def main_handler(event, context):price_check_job()return "Execution completed"
-
可视化监控面板
- 使用Flask/Django开发Web界面
- 实时展示监控状态
- 微信小程序集成
结语:开启你的自动化之旅
通过本文,你已经掌握了:
- ✅ 专业HTML邮件的自动发送
- ✅ 邮件附件的灵活管理
- ✅ 网页数据的精准爬取
- ✅ 价格监控的完整实现
- ✅ 企业级部署方案
自动化不是取代人类,而是将我们从重复劳动中解放,去做更有创造性的工作。 想象一下,当你的脚本在深夜为你监控到心仪商品的折扣,那种“科技服务于人”的成就感,正是编程的魅力所在!