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

人生第一个python脚本:从数据库查询数据并发送邮件

2018-01-22 13:39 267 查看
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
date = time.strftime('%Y-%m-%d')
# 打开数据库连接
conn = MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='',
db ='test',
charset="utf8",
)
# 使用cursor()方法获取操作游标
cur = conn.cursor()

# 使用execute方法执行SQL语句
data = cur.execute("select id,phone,num,name from test.user_info;")

# print data
info = cur.fetchmany(data)

cur.close()
conn.commit()
conn.close()

def dd(info):
s = ""
for i in info:
#print i[0]
#print i[1]
#print i[2]
#print i[3].decode('utf-8')
# 汉字需要 decode 成utf-8
s += '%s;%s;%s;%s#' % ( i[0],i[1],i[2],i[3].decode('utf-8') )
#print s
return s

# print(dd(info))
# print(date)

# 发送邮件
msg_from='123456@QQ.com' #发送方邮箱
passwd='XXXXXX' #填入发送方邮箱的授权码
msg_to='789@qq.com' #收件人邮箱

subject="python邮件测试 + date "#主题
content= str(dd(info)) #正文
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL("smtp.exmail.qq.com",465)#邮件服务器及端口号
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
print "发送成功"
except s.SMTPException,e:
print "发送失败"
finally:
s.quit()

=====================================
系统安装MySQL-python-1.2.5下载 :https://pypi.python.org/pypi/MySQL-python
# yum install –y mysql-devel
安装:
[root@www soft]# unzip MySQL-python-1.2.5.zip[root@www soft]# cd MySQL-python-1.2.5[root@www soft]# python setup.py build[root@www soft]# python setup.py install测试:[root@www soft]# python>>> import MySQLdb>>>安装完毕。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 查询 数据