#!/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 ')
# Open Database connection
conn = MySQLdb.connect (
host= ' localhost ',
Port = 3306,
User= ' Root ',
Passwd= ',
db = ' Test ',
charset= "UTF8",
)
# get an action cursor using the cursor () method
cur = conn.cursor ()
# Execute SQL statements using the Execute method
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 ')
# Chinese characters need decode into 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)
# Send mail
msg_from= ' [email protected] ' #发送方邮箱
Passwd= ' XXXXXX ' #填入发送方邮箱的授权码
msg_to= ' [email protected] ' #收件人邮箱
subject= "python Mail test + date" #主题
content= Str (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 "Sent successfully"
Except S.smtpexception,e:
Print "Send Failed"
Finally
S.quit ()
=====================================
System Installation mysql-python-1.2.5
Download: Https://pypi.python.org/pypi/MySQL-python
# yum Install–y mysql-devel
Installation:
[Email protected] soft]# Unzip Mysql-python-1.2.5.zip
[email protected] soft]# CD mysql-python-1.2.5
[email protected] soft]# python setup.py build
[email protected] soft]# python setup.py Install
Test:
[email protected] soft]# python
>>> Import MySQLdb
>>>
Installation is complete.
The first Python script in life: Querying data from a database and sending a message