使用Python基于SQL查询结果实现带xlsx附件的月度邮件定时发送
定时执行Python报表脚本的实现方案
你当前的代码已经完成了SQL查询、Excel生成、邮件组装的逻辑,只需要补全发送逻辑再加上定时触发规则即可,下面给出两种Windows环境下最常用的实现方案:
方案1:使用Windows自带任务计划程序(推荐,无需修改太多现有代码)
适合个人办公电脑使用,无需额外安装依赖,操作步骤如下:
- 先调整现有代码:在现有代码最后添加一行
message.Send(),你当前的代码仅完成了邮件和附件的组装,没有执行发送操作,这行不能省略。 - 把修改好的代码保存为
.py格式的文件,比如monthly_sales_report.py,确认所有占位符(服务器ID、数据库名、SQL语句、文件路径、邮箱地址等)都已替换为实际值。 - 本地测试脚本可正常运行:按下Win+R输入
cmd打开命令提示符,执行python 你的脚本完整路径\monthly_sales_report.py,确认可以正常生成Excel文件且收件人能收到邮件后再进行后续操作。 - 按下Win+S搜索「任务计划程序」打开,点击右侧菜单的「创建基本任务」:
- 自定义任务名称(比如「月度报表自动发送」),点击下一步
- 触发器选择「每月」,点击下一步后设置你需要的发送日期、具体执行时间
- 操作选择「启动程序」,点击下一步
- 「程序或脚本」输入框填Python解释器的完整路径(不知道路径的可以在cmd里执行
where python查询),比如C:\Python310\python.exe - 「添加参数」输入框填你保存的脚本的完整路径,注意如果路径包含空格要用英文双引号包裹,比如
"D:\work scripts\monthly_sales_report.py" - 点击完成即可,你可以右键刚创建的任务选择「运行」,测试是否能正常触发执行。
方案2:使用Python定时任务库APScheduler(适合服务器常驻运行场景)
如果脚本要放在服务器上运行,可以直接用Python的定时任务库实现,操作步骤如下:
- 先安装依赖库:打开cmd执行
pip install apscheduler - 在现有代码基础上新增调度逻辑即可,示例代码如下:
import pyodbc import pandas as pd import win32com.client as client import pathlib from apscheduler.schedulers.blocking import BlockingScheduler # 把你原有业务逻辑封装成函数 def send_monthly_report(): conn = pyodbc.connect('Driver={SQL Server};' 'Server=[ServerID];' 'Database=[Name of Database];' 'Trusted_Connection=yes;') cursor = conn.cursor() #Insert SQL query sql_query = pd.read_sql_query('''[MY SQL QUERY]''',conn) #write to new workbook given file path and new document name writer = pd.ExcelWriter(r'Directory\Filename.xlsx', engine='xlsxwriter') # define the new workbook and sheet to place data on sql_query.to_excel(writer, startrow = 0, sheet_name='Sheet1', index=False) #Indicate workbook and worksheet for formatting workbook = writer.book worksheet = writer.sheets['Sheet1'] #Update row width to fit text for i, col in enumerate(sql_query.columns): # find length of column i column_len = sql_query[col].astype(str).str.len().max() # Setting the length if the column header is larger # than the max column value length column_len = max(column_len, len(col)) + 2 # set the column length worksheet.set_column(i, i, column_len) # Close the Pandas Excel writer and output the Excel file. writer.save() excel_path = pathlib.Path(r'Directory\Filename.xlsx') str(excel_path.absolute()) excel_absolute = str(excel_path.absolute()) outlook = client.Dispatch("Outlook.Application") #0 represents new mail items message = outlook.CreateItem(0) message.To = "myemailaddress@outlook.com" message.CC = "managersemailaddress@outlook.com" message.Subject = "Automated Report" message.body = "Hello - Please see attached report which includes all data you requested. This will be provided to you on a monthly basis." message.Attachments.Add(excel_absolute) # 新增发送逻辑 message.Send() if __name__ == '__main__': # 设置时区避免时间偏差 scheduler = BlockingScheduler(timezone='Asia/Shanghai') # 定时规则可自定义,下方示例为每年每月1号上午9点执行,可按需调整day、hour、minute参数 scheduler.add_job(send_monthly_report, 'cron', month='*', day=1, hour=9, minute=0, second=0) print('月度报表定时任务已启动,等待触发...') scheduler.start()
- 注意该方案需要脚本保持后台运行,电脑关机则任务不会触发,建议放在7*24小时运行的服务器上使用。
内容的提问来源于stack exchange,提问作者Mystical Me
相关产品推荐
相关产品推荐

