尝试发送电子邮件Python时出错

时间:2016-03-16 01:25:38

标签: python email gmail smtplib

好吧,我正在尝试制作一个程序,用python给某人发送电子邮件,在论坛上还有其他类似的东西,但是我已经做了这些更改而且它们似乎不起作用,我认为smtplib已经改变,供参考我正在使用python 2.7

这是代码

#sending email with python
import smtplib
TO="example2@gmail.com"
SUBJECT = 'Sending an email yo'
TEXT = 'YOLO'

gmail_sender = "example@gmail.com"
gmail_passwd = 'pass'

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)

BODY = '\r\n'.join([
    'To: %s' % TO,
    'From: %s' % gmail_sender,
    'Subject: %s' % SUBJECT,
    '',
    TEXT
    ])

try:
    server.sendmail(gmail_sender, [TO], BODY)
except:
    print('ERROR!!!!!')
server.quit()

建议进行更改后,这是新错误:

Traceback (most recent call last):
File "C:\Users\hack\Desktop\yolo.py", line 10, in <module>
server = smtplib.SMTP('smtp.gmail.com', 587)
File "C:\Python34\lib\smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python34\lib\smtplib.py", line 321, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python34\lib\smtplib.py", line 292, in _get_socket
self.source_address)
File "C:\Python34\lib\socket.py", line 512, in create_connection
raise err
File "C:\Python34\lib\socket.py", line 503, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because                       
the target machine activley refused it

1 个答案:

答案 0 :(得分:1)

这是由您的脚本名称引起的 - &#39; email.py&#39;。因为Python已经有email个包。重命名您的脚本将解决它。