我正在尝试设置一个简单的 Webhook 应用程序来接收请求并根据有效负载发送电子邮件。使用的库是用于 SMTP 的 smtplib、用于托管的 Flask 和用于隧道的 ngrok,以使其公开可用。
问题在于 SMTP 连接行为异常。我尝试对连接保持保守,只让它们打开足够长的时间以在断开连接之前发送电子邮件 - 这不应该是一个问题,因为我不希望它收到大量流量,可能会收到 5 个请求一周。
如果我省略
server.connect()
,那么它将运行一次,并且后续连接将失败并出现错误 please use connect() first
。但是,当我包含 connect()
函数时,它根本不起作用,并出现错误
[WinError 10061] No connection could be made because the target machine actively refused it
以下是截断的代码:
webapp = Flask(__name__)
mailServer = "smtp.office365.com"
port = 587
sender = 'sendermail'
receivers = 'recipientmail'
password = securepassword
server = SMTP(mailServer, port)
def strtngrok():
# do stuff
def connectEmail():
# declarations for mail in smtplib, and opening TLS session
print("Connecting to SMTP Server")
try:
emContext = create_default_context()
server.connect()
server.ehlo()
server.starttls(context = emContext)
server.login(sender, password)
except SMTPException as e:
print("Unable to establish connection to SMTP Server")
print(e)
return 501
print("SMTP Server connected\n")
return
# End declarations for mail
def generateEmail (payload):
# do stuff
msg.attach(MIMEText(html, "html"))
if connectEmail() == 501:
return 501
server.sendmail(sender, receivers.split(","), msg.as_string())
server.close()
return
@webapp.route('/mywebhook', methods=['POST'])
def return_response():
# do stuff
if __name__ == "__main__":
context = SSLContext(PROTOCOL_TLS_SERVER)
strtngrok()
webapp.run(host = "0.0.0.0", port=1453)
我想也许我混淆了一些 SMTP 命令,交换了
ehlo()
和 login()
的位置,但没有运气。
我曾考虑过设置一个连接并将其保持打开状态,但它不会收到足够频繁的请求来保持连接处于活动状态,因此它很快就会超时。
我是否应该为 SMTP 连接创建 2 个单独的函数,一个用于初始连接,一个用于重新连接?或者我是否混淆了 SMTP 连接的顺序? 我不认为这是我们服务器端的安全问题,因为我们有多个小型应用程序使用类似的连接方法来发送电子邮件,与此的主要区别在于它需要稍后重新连接。
所有帮助将不胜感激
我已经通过更改服务器声明的位置成功解决了这个问题。 通过将其放入
connectEmail
函数中,并将其转换为全局变量,它允许后续会话正常工作。
def connectEmail():
# declarations for mail in smtplib, and opening TLS session
print("Connecting to SMTP Server")
try:
# declaring the SMTP server within the function, instead of using the old stale session
global server
server = SMTP(mailServer, port)
emContext = create_default_context()
server.starttls(context = emContext)
server.ehlo()
server.login(sender, password)
except Exception as e:
print("Unable to establish connection to SMTP Server")
print(e)
return 501
print("SMTP Server connected\n")
return 200