Python在Body Email中发送MySQL查询

时间:2018-05-29 18:18:30

标签: python mysql sql email

你好!我需要帮助。我有一个脚本,连接到mysql并打印查询。

from __future__ import print_function

import MySQLdb as my

db = my.connect(host="127.0.0.1",
    user="root",
    passwd="",
    db="gs"
    )

cursor = db.cursor()

sql = "
SELECT c.titulo as Control
     , IF(c.responsable=1, 'TISO','FISO')  AS Responsable
     , case r.mes  when 1 then 'Enero'  when 2 then 'Febrero'  when 3 then 'Marzo' when 4 then 'Abril' when 5 then 'Mayo' when 6 then 'Junio' when 7 then 'Julio' when 8 then 'Agosto' when 9 then 'Septiembre' when 10 then 'Octubre' when 11 then 'Noviembre' when 12 then 'Diciembre'  end AS Mes 
  FROM controles AS c 
  JOIN referencias as r 
    ON c.id_control = r.id_control 
 WHERE r.mes <= MONTH(CURRENT_DATE()) 
   AND r.ano = YEAR(CURRENT_DATE()) 
 ORDER 
    BY c.responsable
     , c.titulo
     , r.mes ASC
"

number_of_rows = cursor.execute(sql)

result = cursor.fetchall()

fiso = 0
tiso = 0


for row in result:
    if (row[1]=='TISO' and tiso == 1):
        print(row[1], row[0],' | ',row[2])
    if (row[1]=='TISO' and tiso == 0):
        print ("--------------------------------------------------")
        print ("                 Controles TISO                   ")
        print ("--------------------------------------------------")
        tiso = 1
        print(row[1], row[0],' | ',row[2])
    if (row[1]=='FISO' and fiso == 1):
        print(row[1], row[0],' | ',row[2])
    if (row[1]=='FISO' and fiso == 0):
        print ("--------------------------------------------------")
        print ("                 Controles FISO                   ")
        print ("--------------------------------------------------")
        fiso = 1
        print(row[1], row[0],' | 'row[2])


db.close()

这里是结果

enter image description here

如何将此结果添加到电子邮件正文?

我将与此脚本合并

smtplib module send mail

import smtplib

TO = 'XXXXXX@gmail.com'
SUBJECT = 'XXXXXX'
TEXT = 'MESSAGE.'

# Sign In
gmail_sender = 'XXXX@gmail.com'
gmail_passwd = 'XXXXX'

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)

BODY = '\r\n'.join(['To: %s' % TO,
                    'From: %s' % gmail_sender,
                    'Subject: %s' % SUBJECT,
                    '', TEXT])

try:
    server.sendmail(gmail_sender, [TO], BODY)
    print ('email sent')
except:
    print ('error sending mail')

server.quit()
你能帮帮我吗?我是火车将每一行添加到TEXT变量,但我不知道如何管理元组。

谢谢大家!

0 个答案:

没有答案