我想检查我是否可以从我的 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b080e08111a3b1c161a121755181416" rel="noreferrer noopener nofollow">[email protected]</a>"
family = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254150564f44654248444c490b464a48" rel="noreferrer noopener nofollow">[email protected]</a>"
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 协议(protocol) - 您需要使用您的 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/