【问题标题】:How can I hold a SMTP connection open with smtplib and Python?如何使用 smtplib 和 Python 保持打开的 SMTP 连接?
【发布时间】:2010-10-20 13:04:22
【问题描述】:

我需要检查 SMTP 服务器的超时,但我的套接字刚刚关闭。我究竟做错了什么?这是我的测试:

#!/usr/bin/python
import smtplib
import time
import datetime
import socket
socket.setdefaulttimeout(1800)


now = time.time()
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect('mx.foo.bar','25')
(code,resp) = server.docmd('NOOP')
then = time.time()

print then-now

希望这行得通。

【问题讨论】:

  • 为什么要这样做?你连接,你发送你的邮件,你断开连接。如果您不使用它,为什么要保持连接打开?
  • 我正在尝试检查 RFC 合规性。建议使用 Python 而不是 C,因为它易于使用。

标签: python sockets smtp smtplib


【解决方案1】:

嗯,我还没有找到任何方法来保持与 smtplib 的 smtp 连接打开。

但是,如果你想重用一个连接而不关闭(是的,打开一个 连接需要时间,2-3 秒),您可以先测试连接。 为此,请发出 NOOP 命令并测试状态 == 250。如果不是,那么您 可以打开连接并发送您的邮件。并且您可以选择在完成之前不退出()连接。

import smtplib

def create_conn():
    conn = smtplib.SMTP('smtp.gmail.com', 587)
    ...
    return conn

def is_connected(conn):
    try:
        status = conn.noop()[0]
    except:  # smtplib.SMTPServerDisconnected
        status = -1
    return True if status == 250 else False

【讨论】:

  • @Ethan- 有道理!
  • @trex 谢谢。而且效果很好,在过去 2 年多的时间里,我一直在成功使用它,没有任何问题。
  • 这是一种阻塞方法。有超时吗?
  • 这很好用,创建一个全局变量 smtp_connection 并在你的 create_conn 函数中检查 is_connected(smtp_connection) ,它将重复使用相同的连接,直到其关闭或超时。
【解决方案2】:

您确定要断开连接吗?当我在后缀服务器上运行上述代码时,我得到:

connect: ('server', '25')
connect: ('ip.address', 25)
reply: '220 server ESMTP Postfix\r\n'
reply: retcode (220); Msg: nserver ESMTP Postfix
connect: server ESMTP Postfix
send: 'NOOP\r\n'
reply: '250 2.0.0 Ok\r\n'
reply: retcode (250); Msg: 2.0.0 Ok
0.0531799793243

docmd 不会阻塞,服务器响应并且程序退出。因此,我在程序退出时断开连接。

如果我打开 python 命令行并执行:

>> import smtplib
>> server = smtplib.SMTP()
>> server.connect('server')
>> server.docmd('NOOP')
(250, '2.0.0 Ok')
>> ## let it sit for 5 minutes
>> server.docmd('NOOP')
(421, '4.4.2 server Error: timeout exceeded')

我的日志证实了这一点:

Oct 20 10:45:35 [postfix/smtpd] connect from unknown[ip.address]
Oct 20 10:50:10 [postfix/smtpd] timeout after NOOP from unknown[ip.address]

【讨论】:

    【解决方案3】:

    检查您的邮件服务器设置 - 它们可能会切断连接。

    【讨论】:

    • 我检查的每个 MTA 都会发生这种情况。他们得到命令,返回 220,然后连接关闭。使用 telnet 我在 5 分钟后超时。
    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    • 2019-12-05
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2012-04-22
    • 2013-11-09
    相关资源
    最近更新 更多