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

Python获取Mysql数据并Mail

2017-06-06 15:02 281 查看
1、通过126邮箱发送的脚本

/Users/nisj/PycharmProjects/BiDataProc/MailMysqlData/DataGetAndMailSend(126Send).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,name,phone_num,qq,area,created_time FROM match_apply where match_id = 83;">/root/MailMysqlData/huoyingrenzhe_enroll_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,name,phone_num,qq,area,created_time FROM match_apply where match_id = 83 order by created_time desc;"
curr.execute(sql_text)
html_data = "<tr style='font-weight:bold;'><td>用户ID</td><td>姓名</td><td>电话号码</td><td>QQ号码</td><td>区域学校</td><td>报名时间</td>></tr>"
items = curr.fetchall()
for item in items:
item0 = str(item[0])
item1 = str(item[1])
item2 = item[2]
item3 = item[3]
item4 = str(item[4])
item5 = str(item[5])

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

curr.close()
conn.close()

sender = "nsj820@126.com"
rcpt = ["shijia.ni@kascend.com", "nsj820@126.com"]

msg = MIMEMultipart('alternatvie')
msg['Subject'] = Header("火影校园赛赛事实时报名-按小时汇报", "utf-8")  # 组装信头
msg['From'] = sender  # 使用国际化编码
msg['To'] = ', '.join(rcpt)

html = "Hi All:<br>这是最新的火影校园赛赛事实时报名-按小时汇报信息,每小时全量发送播报一次,请查收!<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/huoyingrenzhe_enroll_info.txt"
att_file_name = "attachment; filename=\"huoyingrenzhe_enroll_info.txt\""
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', 'Mail126'sPasswd')
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、通过阿里邮箱发送的脚本

/Users/nisj/PycharmProjects/BiDataProc/MailMysqlData/DataGetAndMailSend(AliSend).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,name,phone_num,qq,area,created_time FROM match_apply where match_id = 83;">/root/MailMysqlData/huoyingrenzhe_enroll_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,name,phone_num,qq,area,created_time FROM match_apply where match_id = 83 order by created_time desc;"
curr.execute(sql_text)
html_data = "<tr style='font-weight:bold;'><td>用户ID</td><td>姓名</td><td>电话号码</td><td>QQ号码</td><td>区域学校</td><td>报名时间</td>></tr>"
items = curr.fetchall()
for item in items:
item0 = str(item[0])
item1 = str(item[1])
item2 = item[2]
item3 = item[3]
item4 = str(item[4])
item5 = str(item[5])

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

curr.close()
conn.close()

sender = "shijia.ni@kascend.com"
rcpt = ["shijia.ni@kascend.com", "nsj820@126.com"]

msg = MIMEMultipart('alternatvie')
msg['Subject'] = Header("火影校园赛赛事实时报名-按小时汇报", "utf-8")  # 组装信头
msg['From'] = sender  # 使用国际化编码
msg['To'] = ', '.join(rcpt)

html = "Hi All:<br>这是最新的火影校园赛赛事实时报名-按小时汇报信息,每小时全量发送播报一次,请查收!<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/huoyingrenzhe_enroll_info.txt"
att_file_name = "attachment; filename=\"huoyingrenzhe_enroll_info.txt\""
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.mxhichina.com')  # 登录SMTP服务器,发信
s.login('shijia.ni@kascend.com', 'MailAli'sPasswd')
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!"


3、发送测试

[root@master MailMysqlData]# ll
total 32
-rw-r--r-- 1 root root  3245 Jun  6 14:31 DataGetAndMailSend(126Send).py
-rw-r--r-- 1 root root  3268 Jun  6 14:31 DataGetAndMailSend(AliSend).py
-rw-r--r-- 1 root root 18336 Jun  6 10:28 DataSendAndMailSend.log
-rw-r--r-- 1 root root  3239 Jun  1 17:42 DataSendAndMailSend.py
[root@master MailMysqlData]# python DataGetAndMailSend\(126Send\).py
Warning: Using a password on the command line interface can be insecure.
2017-06-06 14:32:16 Mail Send Finished!
[root@master MailMysqlData]# python DataGetAndMailSend\(AliSend\).py
Warning: Using a password on the command line interface can be insecure.
2017-06-06 14:33:18 Mail Send Finished!
[root@master MailMysqlData]# ll
total 56
-rw-r--r-- 1 root root  3245 Jun  6 14:31 DataGetAndMailSend(126Send).py
-rw-r--r-- 1 root root  3268 Jun  6 14:31 DataGetAndMailSend(AliSend).py
-rw-r--r-- 1 root root 18336 Jun  6 10:28 DataSendAndMailSend.log
-rw-r--r-- 1 root root  3239 Jun  1 17:42 DataSendAndMailSend.py
-rw-r--r-- 1 root root 23139 Jun  6 14:33 huoyingrenzhe_enroll_info.txt
[root@master MailMysqlData]#


4、邮件发送CronTab定时

28 10 * * * /usr/bin/python /root/MailMysqlData/DataSendAndMailSend.py >> /root/MailMysqlData/DataSendAndMailSend.log 2>&1


5、说明

上文中,1和2实际上是一样的,只是邮件发送者邮箱改了一下。126邮箱频繁发送不存在问题,但阿里邮箱发送太过频繁的话可能出现发不出或接收不到的情况,怀疑是阿里邮箱限制所致(定时每小时发送一次则可正常运行)。脚本能正常运行的前提是,对应的服务器上smtplib和MySQLdb模块先安装好;且脚本在服务器上的路径是【/root/MailMysqlData/】。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: