質問

I've written a small Python daemon that receives mail from the local, network and sends it via an external mail provider. The problem is that if once a connection is established, I can send an email once, but not another. The following code shows the problem:

I connect the server like so:

>>> from smtplib import SMTP
>>> smtp = SMTP()
>>> smtp.connect('mail.gmx.net', 587)
(220, b'gmx.com (mrgmx003) Nemesis ESMTP Service ready')
>>> smtp.login('XXX', 'XXX')
(235, b'Authentication succeeded')
>>> smtp.sendmail('XXX', 'XXX', '')
{}
>>> smtp.quit()
(221, b'gmx.com Service closing transmission channel')

Everything works fine, the email is sent. But if I do the same thing later, I get an error "503 Bad sequence of commands". The connect still works:

>>> smtp.connect('mail.gmx.net', 587)
(220, b'gmx.com (mrgmx003) Nemesis ESMTP Service ready')

but neither this works:

>>> smtp.login('XXX', 'XXX')
(503, b'Bad sequence of commands')

nor this:

>>> smtp.sendmail('XXX', 'XXX', '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.2/smtplib.py", line 749, in sendmail
    raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (503, b'Bad sequence of commands', 'XXX')

So, what's wrong here? If I do the whole thing again, starting with "smtp = SMTP()", everything works again. Shouldn't "smtp.quit()" reset the connection?

Thanks for all help!

役に立ちましたか?

解決

You are missing smtp.ehlo('XXX') in the second session. Try adding it immediately after the .connect(). The EHLO or HELO, as the case may be, is implicitly sent in the first session, but not in the second. If you send it explicitly, then your example will work.

This is arguably a bug in the smtplib.

他のヒント

It seems fairly clear that the author of this SMTP class did not intend for instances to be recycled after quit(). Create a new instance instead.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top