0

我有一个用 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
4

1 回答 1

1

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

改变

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

  msg.attach(MIMEImage(open(attachment,'rb').read()))
于 2021-03-17T21:18:04.507 回答