我正在编写一个python脚本,它将从表中读取数据,然后向用户发送一条消息,包括查询返回的每一行的列信息,脚本如下所示:
#!/usr/bin/python
import smtplib
import psycopg2
connection = psycopg2.connect(user="postgres",
password="postgres",
host="localhost",
port="5432",
database="myDB")
db_cursor = connection.cursor()
s = "SELECT error_message FROM temp.data_upload_errors"
db_cursor.execute(s)
try:
array_rows = db_cursor.fetchall()
except psycopg2.Error as e:
t_message = "Postgres Database error: " + e + "/n SQL: " + s
#return render_template("error.html", t_message = t_message)
db_cursor.close()
sender = 'email@provider.com'
receivers = ['email@provider.com']
for t_item in array_rows:
msg = "Error Message: " , t_item , "<br>"
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
但是,我得到了这个错误:
AttributeError:“tuple”对象没有属性“as_string”
我希望返回'msg'下的全部内容,而不仅仅是[0]或[1]数组项。
我是Python的新手,所以不知道哪里出了问题。
谢谢,
首先,请注意
msg = "Error Message: " , t_item , "<br>"
与
msg = ("Error Message: " , t_item , "<be>")
因此您的msg
实际上是一个元组。
另一方面,实际上每次在for循环中都在覆盖它
for t_item in array_rows:
msg = "Error Message: " , t_item , "<br>"
因此msg
将只包含数组中的最后一项。
我认为你真正需要做的是
msg = "<br>".join("Error Message: " + "".join(t_item) for t_item in array_rows)
(“”.join(t_item)
需要正确地将每个项从元组
转换为字符串
)。
你试过把这行换行成打印语句吗
例如。
打印(smtpobj.sendmail(发送者,接收者,msg.as_string())
否则,可以使用以下方法包括所有元素:
消息[:]
其他您也可以使用“”。join(msg)
,因为它是元组[如果您想在一行中全部使用]