我想检查一下我是否可以从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 = "[email protected]"
family = "[email protected]"
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
最佳答案
上面的代码序列中似乎缺少三件事:
你需要使用587端口
需要调用starttls()
才能切换到SSL/TLS协议
您需要使用Gmail用户名和密码通过调用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()
关于python - 如何检查我可以发送电子邮件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22162152/