我想检查一下我可以从我的python程序发送电子邮件。不幸的是它失败了,它看起来因为SMTP服务器不接受我的电话。 我只需要检查我的程序是否正确,我可以发送电子邮件......但我没有检查它。 这是我的程序,如何让服务器接受我的电话?
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
me = "susja@gmail.com"
family = "dusja@gmail.com"
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'
# Send the email via our own SMTP server.
s = smtplib.SMTP('smtp.gmail.com')
s.sendmail(me, family, msg.as_string())
s.quit()
我有这个错误:
Traceback (most recent call last):
File "2.py", line 21, in <module>
s = smtplib.SMTP('smtp.gmail.com')
File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.7/socket.py", line 562, in create_connection
sock.connect(sa)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
KeyboardInterrupt
答案 0 :(得分:5)
上面的代码序列中似乎缺少三件事:
starttls()
才能切换到SSL / TLS协议login
来登录Gmail SMTP服务器。 您的代码的最后一部分现在应如下所示:
s = smtplib.SMTP_SSL("smtp.gmail.com", 587)
s.starttls()
s.login('gmail_username', 'gmail_password')
s.sendmail(me, family, msg.as_string())
s.close()
答案 1 :(得分:0)
对于遇到与AWS和Flask类似问题的任何人,我发现的解决方案是设置环境变量MAIL_USE_TLS=True
。同样这只适用于flask.ext.mail,但它可能会为将来节省一些时间和精力。