Python 自动发送数据库报表邮件 - 从本月1号到昨日数据
首先,你需要安装 Python 的数据库驱动程序,比如 MySQLdb 或者 psycopg2,然后连接到数据库并编写查询语句。假设你使用的是 MySQL 数据库,下面是一个示例代码:
import MySQLdb
import datetime
import smtplib
from email.mime.text import MIMEText
# 连接数据库
conn = MySQLdb.connect(host='localhost', user='root', passwd='password', db='mydb')
cursor = conn.cursor()
# 查询数据
today = datetime.date.today()
first_day = today.replace(day=1)
yesterday = today - datetime.timedelta(days=1)
query = 'SELECT * FROM mytable WHERE date BETWEEN '%s' AND '%s'' % (first_day, yesterday)
cursor.execute(query)
result = cursor.fetchall()
# 发送邮件
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_email@gmail.com'
smtp_password = 'your_password'
sender = 'your_email@gmail.com'
recipients = ['recipient1@example.com', 'recipient2@example.com']
subject = 'Data report from mytable'
body = 'Here is the data from mytable:
' + str(result)
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ', '.join(recipients)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()
# 关闭数据库连接
cursor.close()
conn.close()
上面的代码中,我们先连接到 MySQL 数据库,并使用当前日期计算本月 1 号和昨天的日期,然后编写 SQL 查询语句,查询 mytable 表中在这个日期范围内的数据,并将结果存储在 result 变量中。接着,我们使用 Python 内置的 smtplib 模块来发送电子邮件。你需要准备一个 Gmail 邮箱账号,并将你的邮件地址和密码替换成代码中的 smtp_username 和 smtp_password。然后,指定邮件的发送者、接收者、主题和正文,并将查询结果作为邮件的正文。最后,我们使用 SMTP 服务器发送邮件,并关闭数据库连接。
请注意,上面的代码仅供参考,你需要根据你的具体情况进行修改。比如,你需要根据你的数据库类型和电子邮件服务提供商来选择适当的 Python 库和配置参数。同时,你还需要确保你的代码能够安全地处理敏感数据,比如数据库密码和邮件账号密码。
原文地址: https://www.cveoy.top/t/topic/lDyn 著作权归作者所有。请勿转载和采集!