I have a program written in python 2.7, which sends a photo attached to an email. So far I have not had any problems but because I use it and other things in my program I have to upgrade it to python 3 and I encounter the following problems:
def sendEmail(self, q, Subject, textBody, attachment, receiver):
"""This method sends an email"""
EMAIL_SUBJECT = Subject
EMAIL_USERNAME = 'sistimaasfalias@gmail.com' #Email address.
EMAIL_FROM = 'Home Security System'
EMAIL_RECEIVER = receiver
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
GMAIL_PASS = 'HomeSecurity93' #Email password.
TEXT_SUBTYPE = "plain"
#Create the email:
msg = MIMEMultipart()
msg["Subject"] = EMAIL_SUBJECT
msg["From"] = EMAIL_FROM
msg["To"] = EMAIL_RECEIVER
body = MIMEMultipart('alternative')
body.attach(MIMEText(textBody, TEXT_SUBTYPE ))
#Attach the message:
msg.attach(body)
msgImage = MIMEImage(file.read())
#Attach a picture:
if attachment != "NO":
msg.attach(MIMEImage(file(attachment).read()))
ERROR MESSAGE:
Process Process-2:2:
Traceback (most recent call last):
File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
self.run()
File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "/home/pi/homesecurity/functions.py", line 233, in sendEmail
msgImage = MIMEImage(file.read())
NameError: name 'file' is not defined
The error is correct. You haven't defined file
. In Python 2, file
was a built-in type, but that no longer exists. The msgImage=MIMEImage(file.read())
would never have made sense, but you aren't using that variable anyway. Delete that line.
Change
msg.attach(MIMEImage(file(attachment).read()))
to
msg.attach(MIMEImage(open(attachment,'rb').read()))