您的位置:首页 > 编程语言 > Python开发

Python获取Mysql数据并Mail(多个附件的添加)

2017-06-14 16:41 253 查看
本文是【Python获取Mysql数据并Mail-->http://blog.csdn.net/babyfish13/article/details/72878198】的继续。
1、带多个附件邮件发送脚本

/Users/nisj/PycharmProjects/BiDataProc/MailMysqlData/DataGetAndMailSend_moreAttachment.py
# -*- coding=utf-8 -*-
import smtplib
import MySQLdb
import warnings
import datetime
import time
import os
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

warnings.filterwarnings("ignore")

os.system("""source /etc/profile;/usr/bin/mysql -hMysqlHostIp -P50512 -uMysqlUser -pMysqlPass -Dtv_event -e"select uid 用户Uid,case when type=1 then '普通奖品' when type=2 then '限量奖品' end 奖品类型,case when award_id=2 then 'iphone7'
when award_id=3 then 'ipad air 2'
when award_id=4 then '小触周边充电宝'
when award_id=5 then '小触周边浴巾'
when award_id=7 then '珍珠'
when award_id=54 then '恶魔果实'
when award_id=24 then '海豚'
when award_id=6 then '海马'
when award_id=9 then '2000Q币'
when award_id=10 then '1000Q币'
when award_id=11 then '100Q币'
when award_id=12 then '翻倍积分奖励'
when award_id=1 then '泡泡'
when award_id=14 then '小触王者铭牌(3天)'
when award_id=15 then '小触紫色昵称(3天)' end 奖品名称,date 日期,created_time,updated_time
from event_award_201611
where event_id =12;">/root/MailMysqlData/jifenchoujiang_info.txt""")

os.system("""source /etc/profile;/usr/bin/mysql -hMysqlHostIp -P50512 -uMysqlUser -pMysqlPass -Dtv_event -e"select uid 用户Uid,case when type=1 then '普通奖品' when type=2 then '限量奖品' end 奖品类型,case when award_id=1 then '王者荣耀全英雄全皮肤'
when award_id=2 then '王者荣耀全英雄'
when award_id=3 then 'KPL总决赛门票'
when award_id=4 then '1000Q币'
when award_id=5 then '小触周边护眼灯'
when award_id=6 then '小触周边充电宝'
when award_id=7 then '海豚'
when award_id=8 then '海马'
when award_id=9 then '海星'
when award_id=10 then '小触钻石铭牌(3天)' end 奖品名称 ,date 日期,created_time,updated_time
from event_award_201611
where event_id =13;">/root/MailMysqlData/jifenduihuan_info.txt""")

db_config = {
'host': 'MysqlHostIp',
'user': 'MysqlUser',
'passwd': 'MysqlPass',
'port': 50512,
'db': 'tv_event'
}

def getDB():
try:
conn = MySQLdb.connect(host=db_config['host'], user=db_config['user'], passwd=db_config['passwd'],
port=db_config['port'])
conn.autocommit(True)
curr = conn.cursor()
curr.execute("SET NAMES utf8");
curr.execute("USE %s" % db_config['db']);

return conn, curr
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return None, None

conn, curr = getDB()

today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)

sql_text = "select uid 用户Uid,point 积分,created_time,updated_time from event_match_bet_point_201705 where match_template_id = 5 order by `point` desc limit 100;"
curr.execute(sql_text)
html_data = "<tr style='font-weight:bold;'><td>用户Uid</td><td>积分</td><td>created_time</td><td>updated_time</td></tr>"
items = curr.fetchall()
for item in items:
item0 = str(item[0])
item1 = str(item[1])
item2 = item[2]
item3 = item[3]

html_data += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (
item0, item1, item2, item3)

curr.close()
conn.close()

sender = "nsj820@126.com"
rcpt = ["zhiqiang.cui@kascend.com", "ziying.wang@kascend.com", "xiaoyuan.yang@kascend.com"]
# rcpt = ["shijia.ni@kascend.com"]

msg = MIMEMultipart('alternatvie')
msg['Subject'] = Header("KPL季后赛竞猜活动", "utf-8") # 组装信头
msg['From'] = sender # 使用国际化编码
msg['To'] = ', '.join(rcpt)

html = "Hi All:<br>这是最新的KPL季后赛竞猜活动积分排名、积分兑换和积分抽奖汇报信息,请查收!(正文是积分排名前100;附件分别是积分兑换和积分抽奖情况)<br><br><table border='1' style='background-color:#22B8DD'>" + html_data + "</table>"
html_part = MIMEText(html, 'html') # 实例化为html部分
html_part.set_charset('utf-8') # 设置编码
msg.attach(html_part) # 绑定到message里

# 构造附件
att_path = "/root/MailMysqlData/jifenchoujiang_info.txt"
att_file_name = "attachment; filename=jifenchoujiang_info"
att = MIMEText(open(att_path, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = att_file_name
msg.attach(att)

att_path = "/root/MailMysqlData/jifenduihuan_info.txt"
att_file_name = "attachment; filename=jifenduihuan_info"
att = MIMEText(open(att_path, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = att_file_name
msg.attach(att)

try:
s = smtplib.SMTP('smtp.126.com') # 登录SMTP服务器,发信
s.login('nsj820@126.com', 'Mail126PassWd')
s.sendmail(sender, rcpt, msg.as_string())
except Exception, e:
print e

print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),"Mail Send Finished!"
2、线上环境

2.1、目录路径
/root/MailMysqlData

2.2、文件清单
[root@master MailMysqlData]# ll
total 64
-rw-r--r-- 1 root root  5128 Jun 14 16:15 DataGetAndMailSend_moreAttachment.py
-rw-r--r-- 1 root root 32298 Jun 14 16:30 jifenchoujiang_info.txt
-rw-r--r-- 1 root root 20394 Jun 14 16:30 jifenduihuan_info.txt
-rw-r--r-- 1 root root   186 Jun 14 16:30 MailSend.log
[root@master MailMysqlData]#

2.3、日志内容
[root@master MailMysqlData]# cat MailSend.log
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
2017-06-14 16:30:04 Mail Send Finished!
[root@master MailMysqlData]#

3、定时调度
[root@master MailMysqlData]# crontab -l
1 1 * * * ntpdate ntp1.aliyun.com
*/30 * * * * /usr/bin/python /root/MailMysqlData/DataGetAndMailSend_moreAttachment.py >> /root/MailMysqlData/MailSend.log 2>&1
[root@master MailMysqlData]#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: