Python 2.7 获得;LazyImporter对象不可调用“;尝试使用python smtplib发送电子邮件时出错
尝试发送电子邮件时出现“LazyImporter对象不可调用”错误 使用gmail中的python smtplib附带附件。 我已在发件人gmail中启用允许较少安全性应用程序设置 代码: 错误:文件“test_mail.py”,第64行,在 发送电子邮件(收件人、主题、文本、附件文件) 文件“test_mail.py”,第24行,在send_email中 msg.attach(MIMEText(text))Python 2.7 获得;LazyImporter对象不可调用“;尝试使用python smtplib发送电子邮件时出错,python-2.7,smtplib,Python 2.7,Smtplib,尝试发送电子邮件时出现“LazyImporter对象不可调用”错误 使用gmail中的python smtplib附带附件。 我已在发件人gmail中启用允许较少安全性应用程序设置 代码: 错误:文件“test_mail.py”,第64行,在 发送电子邮件(收件人、主题、文本、附件文件) 文件“test_mail.py”,第24行,在send_email中 msg.attach(MIMEText(text)) TypeError:“LazyImporter”对象是不可调用的就像@How-abou
TypeError:“LazyImporter”对象是不可调用的就像@How-about-nope所说的,使用import语句导入的是MIMEText模块,而不是类。我可以从你的代码中重现错误。当我从email.mime.text导入时,错误消失了 将import从email.mime.text import MIMEText更改为
,因为现在您正在导入无法调用的模块@How about nope,请尝试使用from email.mime.text import MIMEText。仍然得到相同的错误。可能您现在得到的是:part=MIMEBase('application','octet stream')
-与上面相同的故事,从email.mime.base更改为,导入MIMEBase
@nope如何。按照您的建议在导入中进行更改后,代码现在可以工作了。
import smtplib
from email import MIMEBase
from email import MIMEText
from email.mime.multipart import MIMEMultipart
from email import Encoders
import os
def send_email(to, subject, text, filenames):
try:
gmail_user = 'xx@gmail.com'
gmail_pwd = 'xxxx'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = ", ".join(to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for file in filenames:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com:587") #465,587
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
print('successfully sent the mail')
except smtplib.SMTPException,error::
print str(error)
if __name__ == '__main__':
attachment_file = ['t1.txt','t2.csv']
to = "xxxxxx@gmail.com"
TEXT = "Hello everyone"
SUBJECT = "Testing sending using gmail"
send_email(to, SUBJECT, TEXT, attachment_file)