第一步:安装必要的库
你需要安装 smtplib
(Python 自带),但你需要安装 schedule
和 email
库。你可以使用以下命令安装这些库:
pip install schedule
第二步:编写发送邮件的脚本
这里是一个完整的 Python 脚本示例,它会每天发送一封包含报告的电子邮件:
import smtplib
import schedule
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email():
# 电子邮件的内容
from_addr = 'your_email@example.com'
to_addr = 'recipient_email@example.com'
subject = '每日报告'
body = '这是今天的报告内容。'
# 创建 MIMEMultipart 对象
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 设置 SMTP 服务器
smtp_server = 'smtp.example.com' # 你的 SMTP 服务器
smtp_port = 587 # SMTP 服务器端口
smtp_user = 'your_email@example.com' # 登录 SMTP 服务器的用户名
smtp_pass = 'your_password' # 登录 SMTP 服务器的密码
try:
# 连接到 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 启用 TLS 加密
server.login(smtp_user, smtp_pass) # 登录
# 发送邮件
server.sendmail(from_addr, to_addr, msg.as_string())
print('邮件发送成功')
except Exception as e:
print(f'邮件发送失败: {e}')
finally:
server.quit() # 关闭连接
# 安排每日任务
schedule.every().day.at("09:00").do(send_email) # 每天9点发送邮件
print("任务已安排。")
# 保持脚本运行
while True:
schedule.run_pending()
time.sleep(1)
第三步:设置 SMTP 服务器
- Gmail SMTP 服务器示例:
- SMTP 服务器:
smtp.gmail.com
- 端口: 587
- SMTP 服务器:
如果你使用 Gmail 作为 SMTP 服务器,你需要启用“低安全性应用访问”或者使用应用专用密码。
第四步:运行脚本
将上述脚本保存为 send_email_report.py
文件,然后在终端运行:
python send_email_report.py
这个脚本会每天在设定的时间(这里是每天的 9:00)发送一封电子邮件。如果你希望改变发送时间,可以修改 schedule.every().day.at("09:00").do(send_email)
这一行中的时间。