python 编写自动发送每日电子邮件报告的脚本
发表于:2024-06-04 | 分类: 脚本
字数统计: 705 | 阅读时长: 2分钟 | 阅读量:

Python 编写自动发送每日电子邮件报告的脚本

准备工作:

  • 安装必要的 Python 库,如 smtplib(用于发送邮件)和 email(用于构建电子邮件内容)。
  • 准备邮件服务器的登录凭据和收件人的电子邮件地址。
  • Gmail: SMTP服务器地址是‘smtp.gmail.com’,端口 587
  • Outlook: SMTP服务器地址是‘smtp.office365.com’,端口 587

编写发送邮件的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
import os

def send_email_report():
# 电子邮件服务器和登录信息
smtp_server = 'smtp.office365.com'
smtp_port = 587
sender_email = ‘youremail@outlook.com’
sender_password = 'yourpassword'
receiver_email = 'receiver_email@example.com'

# 创建电子邮件消息
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = f'Daily Report {datetime.date.today().strftime("%Y-%m-%d")}'
body = 'This is the daily report email.'
msg.attach(MIMEText(body, 'plain'))

server = None
try:
# 连接到邮件服务器并发送邮件
server = smtplib.SMTP(smtp_server, smtp_port, timeout=60)
server.set_debuglevel(1) # 打开调试输出
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
print('Email sent successfully.')
except Exception as e:
print(f'Failed to send email: {e}')
finally:
if server:
server.quit()

if __name__ == '__main__':
send_email_report()

设置定时任务:

在 Windows 上使用任务计划程序

  1. 打开任务计划程序:

    • Win + R 打开“运行”对话框,输入 taskschd.msc,然后按 Enter。这将打开任务计划程序。
  2. 创建基本任务:

    • 在任务计划程序窗口中,点击右侧的“创建基本任务”。
  3. 输入任务名称和描述:

    • 在“名称”字段中输入任务名称,例如“Daily Email Report”。
    • 在“描述”字段中输入任务描述(可选)。
    • 点击“下一步”。
  4. 设置任务触发器:

    • 选择“每日”,然后点击“下一步”。
    • 设置任务开始时间,例如每天早上 9 点。点击“下一步”。
  5. 设置任务操作:

    • 选择“启动程序”,然后点击“下一步”。
    • 在“程序/脚本”字段中,浏览选择 Python 可执行文件(例如 python.exe,通常位于 Python 安装目录中)。
    • 在“添加参数”字段中输入 Python 脚本的完整路径,例如 C:\path\to\your_script.py
    • 在“起始于”字段中,可以输入脚本所在目录的路径(可选)。
  6. 完成任务创建:

    • 检查所有设置是否正确,然后点击“完成”。

在 macOS 或 Linux 上:

使用 cron 定时任务工具。

  1. 打开终端,输入 crontab -e 来编辑 cron 表。

  2. 添加以下行(假设脚本路径为 /path/to/your_script.py,并且 Python 可执行文件路径为 /usr/bin/python3):   

  3. 启动脚本
      这表示每天早上 9 点运行脚本。

    1
    0 9 * * * /usr/bin/python3 /path/to/your_script.py
  4. 测试脚本和任务:

  • 手动运行脚本以确保其工作正常。
  • 确认定时任务能够按预期运行,并检查邮件是否按时发送。
上一篇:
自然语言处理
下一篇:
picture