我如何在python中发送电子邮件?此代码无效

时间:2014-01-10 03:12:57

标签: python email python-2.7 smtp attributeerror

import smtplib
#SERVER = "localhost"

FROM = 'monty@python.com'

TO = ["jon@mycompany.com"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()

当我尝试在终端中的python shell中运行它时,它给了我这个错误:

Traceback (most recent call last):
    File "email.py", line 1, in <module>
        import smtplib
    File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
        import email.utils
    File "/home/pi/code/email.py", line 24, in <module>
        server = smtplib.SMTP('myserver')
AttributeError: 'module' object has no attribute 'SMTP'

smtplib不具备SMTP功能吗? 或者我应该更改我的代码? 谢谢, A.J。

2 个答案:

答案 0 :(得分:9)

您将文件命名为email.py,该文件隐藏了内置的email包。 smtplib尝试导入email.utils时,这会导致循环导入问题。将您的文件命名为其他内容。

答案 1 :(得分:1)

对于使用gmail的附件邮件,请尝试此操作,替换其他smtp服务器的相应值。

 def mail(to, subject, text, files=[]):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   for file in files:
       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)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

示例示例:

attachements_path=[]
attachements_path.append(<file>)
mail(<to_mail_id>,<subject>,<body>,attachements_path)