'Import Python module 'NameError: name 'contact' is not defined' error
I'm going to connect to mysql using Python.
Attempt to create a module file named dbconn.py and import the dbconn module for mysql connection.
However, an error occurs when the variable is not found.
Help me.
# dbconn.py
import pymysql
def contact():
conn = pymysql.connect(host='localhost', user='test', password='test', db='test', charset='utf8')
cursor = conn.cursor()
sql = 'SELECT mail_addr FROM contact'
cursor.execute(sql)
contact = cursor.fetchall()
conn.close()
# mail.py
import dbconn
dbconn.contact
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('[email protected]', 'abcd')
sender = '[email protected]'
for i in contact:
msg = MIMEMultipart('alternative')
msg['Subject'] = 'test'
msg['From'] = sender
msg['To'] = i[0]
~~~~~~~~~~~~~
smtp.sendmail(sender, i[0], msg.as_string())
smtp.quit()
Solution 1:[1]
I thing that your "contact" function needs to
return contact
and then the call on mail.py has to be:
contact = dbconn.contact()
to create the list you want to iterate on.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alessandro Togni |
