python3 msg.attach(MIMEImage(file(attachment).read())) 中的问题

Problem in python3 msg.attach(MIMEImage(file(attachment).read()))

我有一个用python 2.7 编写的程序,它发送附在电子邮件中的照片。到目前为止我还没有遇到任何问题,但是因为我在我的程序中使用它和其他东西我必须将它升级到 python 3 并且我遇到了以下问题:

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()))

错误信息:

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

错误正确。您还没有定义 file。在 Python 2 中,file 是内置类型,但已不存在。 msgImage=MIMEImage(file.read()) 永远不会有意义,但无论如何您都不会使用该变量。删除该行。

改变

  msg.attach(MIMEImage(file(attachment).read()))

  msg.attach(MIMEImage(open(attachment,'rb').read()))