通过python发送mysql select语句

时间:2017-03-16 19:44:08

标签: python mysql email

我正在尝试将select语句插入电子邮件中。桌子 有10行3列,但我不能这样做。代码和错误如下。

#!/usr/bin/env python  
import csv
import MySQLdb
import pysftp
import smtplib
import sys
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
conn =  MySQLdb.connect(XXXX)
#Email Part1 Msg 
part1 = """
To: To Person <>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
"""
sender = ''
receivers = 
x = conn.cursor()
query1=  ("""select * from table""")
smtpObj=smtplib.SMTP('smtp', 25)
smtpObj.sendmail(sender, receivers, x.execute(query1))   

这是错误消息:

Traceback (most recent call last):
  File "test3.py", line 33, in <module>
    smtpObj.sendmail(sender, receivers, x.execute(query1))         
  File "/usr/lib/python2.7/smtplib.py", line 729, in sendmail
    esmtp_opts.append("size=%d" % len(msg))
TypeError: object of type 'long' has no len(

1 个答案:

答案 0 :(得分:1)

您必须将字符串作为第3个参数传递给smtpObj.sendmail()。执行x.execute(query1)后,您必须获取结果并将其转换为字符串。

x.execute(query1)
msg = ""
for row in x.fetchall():
    msg += str(row) # or however you turn a row into a string
smtpObj.sendmail(sender, receivers, msg)