我正在尝试通过电子邮件发送 OTP(我也将其保存在数据库中),尽管我相信我的配置是正确的,因为它登录了,但它不会发送消息(它发送了前两次,然后停止):
message = """Subject: Your OTP
Hi, your your otp is {otp}"""
from_address = "REDACTED"
password = "REDACTED"
context = ssl.create_default_context()
print('xyz')
msg = message.format(otp=otp)
with smtplib.SMTP_SSL(host="smtppro.zoho.eu", port = 465, context=context) as server:
print('xyz')
server.login(from_address, password)
print('logs')
server.ehlo('127.0.0.1') ## i tried the ehlo() as well and without it all together
print(email) ## prints this and then gets stuck
server.sendmail(
from_address,
email,
msg
)
print('sent')
server.quit() ##i may had forgotten to have that the first 2 times
print('quit')
return "OTP sent to your email"
正如您在代码块中看到的那样,我前两次忘记了
quit()
的事情,我想会话可能出了问题。我重新启动了服务器两次,希望能够重置连接。
请注意我在代码块中所做的注释。
密码我用的是我的账户密码和APP密码(仅用于应用程序中),正如我所说,登录没有问题。
一段时间(2-3分钟)后,我在终端中看到:
File "/home/blank/.local/lib/python3.11/site-packages/flask/app.py", line 1469, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/blank/scripts/test/emails.py", line 56, in sendmail
server.sendmail(
File "/usr/lib/python3.11/smtplib.py", line 902, in sendmail
(code, resp) = self.data(msg)
^^^^^^^^^^^^^^
File "/usr/lib/python3.11/smtplib.py", line 580, in data
(code, msg) = self.getreply()
^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/smtplib.py", line 405, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
要尝试的 3 件事:
server.ehlo('127.0.0.1')
替换为 server.ehlo_or_helo_if_needed()
server.ehlo_or_helo_if_needed()
行之后(在 with
行之前)添加 server.login
(因为它是“如果需要”,您可以在 SMTP 对象的每个函数调用中添加它)email.message
生成一个email.message.EmailMessage
对象,您可以将其传递给smtplib.SMTP_SSL
(或来自smtplib
的每个SMTP对象)到函数server.send_message
,而不是手动创建包含原始字符串消息并将其传递给server.sendmail
。