没有属性“SMTP”,尝试在 Python 中发送电子邮件时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16512256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:52:23  来源:igfitidea点击:

No attribute 'SMTP', error when trying to send email in Python

pythonemailsmtpattributeerror

提问by Jacob Kudria

I am trying to send an email in Python:

我正在尝试用 Python 发送电子邮件:

import smtplib


fromaddr = '......................'  
toaddrs  = '......................'  
msg = 'Spam email Test'  

username = '.......'  
password = '.......'

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()

I understand that this is probably not the correct message format.

我知道这可能不是正确的消息格式。

Anyways, I get an error:

无论如何,我收到一个错误:

C:\.....>python email.py
Traceback (most recent call last):
  File "email.py", line 1, in <module>
    import smtplib
  File "C:\.....\Python\lib\smtplib.py", line 47,
 in <module>
    import email.utils
  File "C:\.....\email.py", line 15, in
<module>
    server = smtplib.SMTP('smtp.gmail.com', 587)
AttributeError: 'module' object has no attribute 'SMTP'

I don't quite understand what I am doing wrong here... Anything incorrect?

我不太明白我在这里做错了什么......有什么不正确的吗?

NOTE: All the periods are replacements for password/email/file paths/etc.

注意:所有句点都是密码/电子邮件/文件路径/等的替换。

采纳答案by Blender

Python already has an emailmodule. Your script's name is email.py, which is preventing smtplibfrom importing the built-in emailmodule.

Python 已经有一个emailmodule。您的脚本名称是email.py,这会阻止smtplib导入内置email模块。

Rename your script to something other than email.pyand the problem will go away.

将您的脚本重命名为其他名称email.py,问题就会消失。

回答by Muneer Ahmad

import smtplib
conn = smtplib.SMTP('imap.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.login('[email protected]', 'your_password')

conn.sendmail('[email protected]','[email protected]','Subject: What you like? \n\n Reply Reply Reply')
conn.quit()