# coding=gbk
import smtplib
import MySQLdb
import datetime
import time
from email.mime.text import MIMEText
mail_to = ""
mail_host = "smtp.qq.com"
mail_user = "****@qq.com"
mail_pass = "****"
mail_postfix = "qq.com"
def query_indb() :
db = MySQLdb.connect("****","****","****","****" )
cursor = db.cursor()
sql = "select * from **** where UNIX_TIMESTAMP(create_at)>= UNIX_TIMESTAMP() - 86400 and UNIX_TIMESTAMP(create_at) <= UNIX_TIMESTAMP()"
result = ""
title = ''
try:
cursor.execute(sql)
results = cursor.fetchall()
result = result + "" + str(len(results)) + "\n\n"
num = 1
title = 'New Rigistered Users Count : ' + str(len(results))
header = ''
th = 'New Rigistered Users Count : ' + str(len(results)) + '' \
'
' \
'
' \
'' \
'Id | ' \
'Name | ' \
'Email | ' \
'Company | ' \
'Phone | ' \
'ServiceLevel | ' \
'CreateTime | ' \
'
'
tr = ''
for row in results :
td = ''
if row[2] is None :
user_email = " "
else:
user_email = row[2]
if row[3] is None :
user_company = " "
else:
user_company = row[3]
if row[4] is None :
phone_number = " "
else:
phone_number = row[4]
td = td + '' + str(row[0]) + ' | '
td = td + '' + str(row[1]) + ' | '
td = td + '' + user_email + ' | '
td = td + '' + user_company + ' | '
td = td + '' + phone_number + ' | '
td = td + '' + str(row[11]) + ' | '
td = td + '' + str(row[13]) + ' | '
tr = tr + '' + td + '
'
tr = tr.encode('utf-8')
body = tr
tail='
'
#将内容拼接成完整的HTML文档
mail = header + th + body + tail
return title,mail
except:
print "Error: unable to fecth data"
db.close()
return result
def send_email(mail_to,sub,content) :
me="****<****@[email protected]>"
msg = MIMEText(content,_subtype="html",_charset="gb2312")
msg['Subject'] = sub
msg['From'] = me
msg['To'] = mail_to
try :
server = smtplib.SMTP()
server.connect(mail_host)
server.ehlo()
server.starttls()
server.ehlo()
server.set_debuglevel(1)
server.login(mail_user,mail_pass)
server.sendmail(me,mail_to,msg.as_string())
server.quit()
return True
except Exception, e :
print str(e)
return False
def send_email_result(mail_to,sub,content) :
me="****<****@[email protected]>"
msg = MIMEText(content,_subtype="plain",_charset="gb2312")
msg['Subject'] = sub
msg['From'] = me
msg['To'] = "****@qq.com"
try :
server = smtplib.SMTP()
server.connect(mail_host)
server.ehlo()
server.starttls()
server.ehlo()
server.set_debuglevel(1)
server.login(mail_user,mail_pass)
server.sendmail(me,mail_to,msg.as_string())
server.quit()
return True
except Exception, e :
print str(e)
return False
if __name__ == '__main__' :
(title,result) = query_indb()
now_time = datetime.datetime.now()
yes_time = now_time + datetime.timedelta(days=-1)
if send_email(mail_to,str(yes_time.strftime('%Y-%m-%d')) + ' ' + title,result) == False :
send_email_result("****@qq.com","Registered Users Count Email Send Failed","Registered Users Count Email Send Failed")