Python 错误 email.mime 没有属性 'MIMEMultipart'

Python Error email.mime has no attribute 'MIMEMultipart'

我正在编写一个项目来使用 Raspberry Pi 3 通过 Gmail 发送电子邮件。该项目在我的笔记本电脑上运行良好,但是当我尝试 运行 Raspberry Pi 上的代码时,不断报告以下错误:

email.mime has no attribute 'MIMEMultipart'

我已尝试按照其他地方的建议使用 pip-install 重新安装电子邮件包,但仍未解决问题。我特别困惑,因为这目前适用于我的笔记本电脑,但不适用于 Raspberry Pi 3.

我的代码如下:

import smtplib
import mimetypes
import email
import email.mime.application

FROM = "Sender's address" #This has been removed from this post, but normally contains sender's address
TO = "recipient's address" #This has been removed from this post, but normally contains recipient's address

msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'Greetings'
msg['From'] = FROM
msg['To'] = TO


body = email.mime.Text.MIMEText("""hi""")
msg.attach(body)


filename= "path+filename" #e.g.(C:/Users/Pictures/pic.jpg)
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="jpg")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)

s = smtplib.SMTP('smtp.gmail.com',587)
s.starttls()
s.login('FROM','PASSWORD') #password is actually entered here in my real code, it has been removed from this post
s.sendmail('FROM',['TO'], 
msg.as_string())
s.quit()

提前感谢您提供的任何指导。

这可能是安装问题。 检查您的 python 安装文件夹是否在 Lib/email/mime 文件夹中有文件 multipart.py。 希望这对您有所帮助!

我终于自己弄明白了。在我的代码顶部添加导入语句解决了问题:

from email.mime.multipart import MIMEMultipart