# Python2连接Mysql数据库并发送带附件的邮件
场景说明:公司运营小姐姐经常让我给她拉数据,为了避免重复工作,就搞了这个脚本。所以就有了这篇文章。
# 1、环境说明
## 1.1、开发环境
| 环境 | 版本 | 备注 |
| ------ | ------------ | ---- |
| 系统 | Windows 11 | |
| Python | 2.7.5 | |
| IDE | Pycharm 2022 | |
## 1.2、运营环境
| 环境 | 版本 | 备注 |
| ------ | ---------------- | ---- |
| 系统 | Linux Centos 7.5 | |
| Python | 2.7.5 | |
| | | |
## 1.3、Python安装与配置
省略。请自行百度。
## 1.4、组件安装
首先用PyCharm随便创建一个项目,然后将创建一个python文件,然后将下面内容复制进去即可。
~~~python
#!/usr/bin/env python
# coding=utf-8
import datetime
import os
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import MySQLdb
import xlwt
def createExcel():
workbook = xlwt.Workbook(encoding='utf-8')
return workbook
def createSheet(workbook, sheetname, fields, results):
sheet = workbook.add_sheet(sheetname, cell_overwrite_ok=True)
for ifs in range(0, len(fields)):
sheet.write(0, ifs, fields[ifs][0])
ics = 1
jcs = 0
for ics in range(1, len(results) + 1):
for jcs in range(0, len(fields)):
sheet.write(ics, jcs, results[ics - 1][jcs])
def getDataFromDB(sql, cursor):
cursor.execute(sql)
results = cursor.fetchall()
fields = cursor.description
return fields, results
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
def sendEmail(fileName, fileNameWithoutPath, timeflag):
# 输入Email地址和口令:
from_addr = 'zhgl.info@aliyun.com'
password = 'zhgl123456'
# 输入SMTP服务器地址:
smtp_server = 'smtp.aliyun.com'
smtp_port = 465
# 输入收件人地址:
to_addr_list = ['anyofus4135@qq.com']
content = "积分兑换数明细报表"
# 生成邮件体
msg = MIMEMultipart('utf-8')
msg['From'] = _format_addr(from_addr)
to_addr = []
for addr in to_addr_list:
to_addr.append(_format_addr(addr))
msg['To'] = ','.join(to_addr)
msg['Subject'] = Header(u'用户积分兑换明细' + timeflag, 'utf-8').encode()
body = MIMEText(content,'html','utf-8')
msg.attach(body)
att = MIMEText(open(fileName, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment;filename="%s"' % Header(fileNameWithoutPath, 'utf-8').encode()
msg.attach(att)
# 连接邮件服务器发送邮件
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
# server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
def main():
lastDate = datetime.date.today() - datetime.timedelta(days=1)
timeflagToday = datetime.date.today().strftime('%Y-%m-%d')
# 日志格式 yyyy-MM-dd
timeflag = lastDate.strftime('%Y-%m-%d')
timeflag_02 = lastDate.strftime('%Y%m%d')
conn = MySQLdb.connect(host='192.168.1.88', user='root', passwd='123456`', db='jack', port=3306,
charset='utf8')
cursor = conn.cursor()
sql_charge = "SELECT pro_name 产品名称,CONVERT (AES_DECRYPT(UNHEX(user_mobile),'zhgl-iflytek') USING utf8) 用户手机号,receiver_name 收货人, receiver_address 收货地址,remark 备注,date_format(create_time, '%Y-%m-%d %H:%i:%S') 创建时间 FROM mall_order,mall_product WHERE mall_order.pro_id = mall_product.id"
workbook = createExcel()
fields, results = getDataFromDB(sql_charge, cursor)
createSheet(workbook, "积分兑换明细", fields, results)
cursor.close()
conn.close()
fileNameWithoutPath = "积分兑换明细%s.xls" % (timeflagToday)
fileName = "d:/data/script/%s" % (fileNameWithoutPath)
workbook.save(fileName)
sendEmail(fileName, fileNameWithoutPath, timeflagToday)
os.remove(fileName)
main()
~~~
### 1.4.1、开发环境组件安装
前提首先尝试用Pycharm安装对应的组件,会自动下载相关安装工具包pip。然后再结合下面手动进行安装。
+ 安装MySQLdb组件
MySQLdb组件是用来操作数据库的,我们使用PyCharm创建项目时创建了虚拟环境,将下载好的MySQL-Python文件复制到项目目录虚拟环境>venv>Scripts下面,地址https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python,找到对应版本的whl文件,如下图
![image-20220714104244710](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f77abc1c2f6e480dbb8ddefde5f3b38e~tplv-k3u1fbpfcp-zoom-1.image)
执行命令进行安装
~~~shell
pip install MySQL_python‑1.2.5‑cp27‑none‑win_amd64.whl
~~~
+ 安装xlwt组件
xlwt组件作用是操作excel文件的,下载地址https://pypi.org/project/xlwt/#files,我这里下载的1.3.0版本
![image-20220714105444514](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/65a4c2fa92e3453bbc1c8bc85cda5cd1~tplv-k3u1fbpfcp-zoom-1.image)
执行命令安装xlwt
~~~shell
pip install xlwt-1.3.0-py2.py3-none-any.whl
~~~
以上安装完成后,项目就不报错了,然后请自行替换里面的邮箱、数据库、sql等配置。
### 1.4.2、实际运行环境组件安装
我们运行的服务器python版本也是2.7.5,同样需要安装MySQLdb、xlwt。首先pip工具没有,我们要先安装pip。
~~~shell
yum install python-pip
~~~
安装MySQLdb组件
~~~shell
yum install MySQL-python
~~~
安装xlwt组件
~~~shell
pip install xlwt
~~~
# 2、部署及验证
## 2.1、部署
直接将调整好的脚本文件上传到服务器对应的目录下我这里放到了【/data/script】下面,然后增加执行权限
~~~shell
chmod +x score_charge_reord.py
~~~
![image-20220714112904190](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/96d480f57dc94042850fdf6a583f3d4d~tplv-k3u1fbpfcp-zoom-1.image)
## 2.2、验证
手动执行脚本
~~~shell
python score_charge_reord.py
~~~
查看邮件发送情况,是否收到邮件。
## 2.3、创建系统定时任务
在crond任务调度中增加我们的任务,每天早上9点执行发送脚本。编辑任务调度
~~~shell
crontab -e
~~~
将下面的内容粘贴到文件系统调度配置中
~~~shell
#每天早上九点发送用户积分兑换明细
0 9 * * * python /data/script/score_charge_reord.py >> /data/script/score_charge_reord.log
~~~
重载系统调度服务
~~~shell
service crond reload
~~~
搞完后,以后让运营小姐姐每天9点自己查邮件即可,不会再来找我了。是不是挺爽的。