python - 无法通过 Python 发送电子邮件
问题描述
我尝试使用 gmail smtp 通过 python 发送电子邮件,但收到错误:
代码:
import smtplib
FROM = "mail1@gmail.com"
TO = "mail2@gmail.com"
message = "Hello"
# Send the mail
server = smtplib.SMTP('smtp.gmail.com', 465)
server.ehlo()
server.starttls()
server.login('mail1@gmail.com', 'password')
server.sendmail(FROM, TO, message)
server.quit()
回复:
server = smtplib.SMTP('smtp.gmail.com', 465)
File "C:\Python37\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python37\lib\smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "C:\Python37\lib\smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
解决方案
根据 python 文档中的示例 https://docs.python.org/3/library/smtplib.html
您的代码缺少“发件人:和收件人:”标头
import smtplib
def prompt(prompt):
return input(prompt).strip()
fromaddr = prompt("From: ")
toaddrs = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
while True:
try:
line = input()
except EOFError:
break
if not line:
break
msg = msg + line
print("Message length is", len(msg))
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
运行上面的例子,然后修改你发布的代码。
推荐阅读
- c# - 构造函数不等待 HTTP 请求
- jenkins - 删除凭据时Jenkins 431字段变大
- spring-boot - Spring Boot 无法运行 schema.sql
- r - 带标签条形百分比和缺失条形的问题
- python - 比较 PySpark 中的 3 列
- hadoop - 尝试确认我对 HBase 和 MapReduce 行为的理解
- ruby-on-rails - 构建可操作频道的 Rails 最佳实践是什么?
- html - 无法为 express mutler 获取 html 形式的文件的完整路径名
- keras - Keras 和 Pytorch 之间编码器 - 解码器模型的差异
- ios - 如何在 SwiftUI 中使用 UITest 在多个设备上进行测试