smtplib
发送邮件,以及 email.mime
来创建电子邮件内容。另外,为了让脚本自动定时运行,可以使用操作系统的计划任务工具(如 Linux 的 cron
或 Windows 的 Task Scheduler)。
MIMEText
来创建纯文本电子邮件,或使用 MIMEMultipart
来添加附件或 HTML 内容。
smtplib.SMTP
连接到电子邮件服务器并发送邮件。
cron
,在 Windows 上使用 Task Scheduler。
有些 Python 安装可能没有 smtplib
和 email
模块。它们是 Python 标准库的一部分,不需要额外安装,但如果你想发送 HTML 报告或者添加其他依赖库,可以使用 pip
安装所需库。
pip install email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime
# 邮件服务器的设置
SMTP_SERVER = "smtp.example.com" # 例如Gmail的SMTP服务器: smtp.gmail.com
SMTP_PORT = 587
EMAIL = "your_email@example.com" # 发送邮件的邮箱
PASSWORD = "your_password" # 邮箱密码或应用授权码
# 收件人的邮箱
TO_EMAIL = "recipient@example.com"
def send_email(subject, body):
# 创建MIME消息
msg = MIMEMultipart()
msg['From'] = EMAIL
msg['To'] = TO_EMAIL
msg['Subject'] = subject
# 添加邮件正文内容
msg.attach(MIMEText(body, 'plain'))
try:
# 连接到SMTP服务器并发送邮件
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls() # 启用TLS加密
server.login(EMAIL, PASSWORD)
text = msg.as_string()
server.sendmail(EMAIL, TO_EMAIL, text)
server.quit()
print(f"邮件发送成功: {subject}")
except Exception as e:
print(f"邮件发送失败: {str(e)}")
def daily_report():
# 生成每日报告的内容
today = datetime.now().strftime("%Y-%m-%d")
subject = f"Daily Report for {today}"
body = f"This is the daily report for {today}."
# 发送报告邮件
send_email(subject, body)
if __name__ == "__main__":
daily_report()
邮箱配置:
你需要使用自己的电子邮件服务提供商的 SMTP 设置来替换代码中的 SMTP_SERVER
和 SMTP_PORT
,并输入你的电子邮件和密码。注意,有些邮件提供商(如 Gmail)可能需要生成一个应用专用密码而不是直接使用你的邮箱密码。
Gmail 的配置示例:
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL = "your_email@gmail.com"
PASSWORD = "your_app_specific_password"
允许安全应用访问: 如果你使用 Gmail 发送电子邮件,你可能需要启用 “允许不太安全的应用程序访问” 或者创建一个 “应用程序专用密码”。
Linux - 使用 cron
:
打开 crontab
编辑器:
crontab -e
添加以下条目来每天在固定时间运行脚本(例如,每天早上8点):
0 8 * * * /usr/bin/python3 /path/to/your/script.py
Windows - 使用 Task Scheduler:
python
解释器的路径和脚本的路径。我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=307etcpbyuuc8