0

I'm working on a python script that would read from a table then send a single message to the users including the column information on each row the query returns, the script looks like this:

#!/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"

However, I'm getting this error:

AttributeError: 'tuple' object has no attribute 'as_string'

I'd like to return the whole content under msg, not just the [0] or [1] array item.

I'm new to Python so not sure what may be wrong.

martineau
  • 119,623
  • 25
  • 170
  • 301
Matias
  • 539
  • 5
  • 28

2 Answers2

1

First of all, notice that

msg = "Error Message: " , t_item , "<br>"

is the same as

msg = ("Error Message: " , t_item , "<be>")

so your msg is effectively a tuple.

On the other hand, you are actually overwriting it each time in the for-loop

for t_item in array_rows:
    msg = "Error Message: " , t_item , "<br>"

so your msg will contain only the last item from the array.

I think what you really need to do is something like this

msg = "<br>".join("Error Message: " + " ".join(t_item) for t_item in array_rows)

Here " ".join(t_item) is a generic way to properly convert each item from the array from tuple to str. Taking into account your SQL query, you are selecting only 1 column from the table, thus each t_item is actually a 1-element tuple so you can just use t_item[0] instead.

Gevorg Davoian
  • 484
  • 5
  • 13
  • Thanks, this worked, If I wanted to send this and get the
    work, is there any additional step I would need to do?
    – Matias Jul 24 '20 at 17:01
-1

Have you tried wrapping the line into a print statement

e.g.

  • print(smtpObj.sendmail(sender, receivers, msg.as_string()))

Otherwise you can include all elements using:

  • msg[:]

Other you can use "".join(msg) as well since it's a tuple [if you want it all on one line]

El Combe
  • 56
  • 5