I am trying to insert a select statement into an email. The table
has 10 rows and 3 columns but I'm not able to do it. Code and errors below.
#!/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))
This is the error messsage:
Traceback (most recent call last):
File "test3.py", line 33, in
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(
解决方案
You have to pass in a string as the 3rd argument to smtpObj.sendmail(). After you do x.execute(query1), you have to fetch the results and turn them into a string.
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)