cpython/Lib/smtplib.py

744 lines
26 KiB
Python
Raw Normal View History

#! /usr/bin/env python
'''SMTP/ESMTP client class.
This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP
Authentication) and RFC 2487 (Secure SMTP over TLS).
Notes:
Please remember, when doing ESMTP, that the names of the SMTP service
extensions are NOT the same thing as the option keywords for the RCPT
and MAIL commands!
Example:
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> print s.help()
This is Sendmail version 8.8.4
Topics:
HELO EHLO MAIL RCPT DATA
RSET NOOP QUIT HELP VRFY
EXPN VERB ETRN DSN
For more info use "HELP <topic>".
To report bugs in the implementation send email to
sendmail-bugs@sendmail.org.
For local information send email to Postmaster at your site.
End of HELP info
>>> s.putcmd("vrfy","someone@here")
>>> s.getreply()
(250, "Somebody OverHere <somebody@here.my.org>")
>>> s.quit()
'''
# Author: The Dragon De Monsyne <dragondm@integral.org>
# ESMTP support, test code and doc fixes added by
# Eric S. Raymond <esr@thyrsus.com>
# Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
# by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
# RFC 2554 (authentication) support by Gerhard Haering <gerhard@bigfoot.de>.
2001-01-14 21:36:40 -04:00
#
# This was modified from the Python 1.5 library HTTP lib.
import socket
import re
import email.Utils
import base64
import hmac
2002-07-26 21:38:30 -03:00
from email.base64MIME import encode as encode_base64
from sys import stderr
__all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException",
"SMTPSenderRefused","SMTPRecipientsRefused","SMTPDataError",
"SMTPConnectError","SMTPHeloError","SMTPAuthenticationError",
"quoteaddr","quotedata","SMTP"]
SMTP_PORT = 25
CRLF="\r\n"
2002-07-26 21:38:30 -03:00
OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)
2001-01-14 21:36:40 -04:00
# Exception classes used by this module.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
class SMTPException(Exception):
"""Base class for all exceptions raised by this module."""
class SMTPServerDisconnected(SMTPException):
"""Not connected to any SMTP server.
This exception is raised when the server unexpectedly disconnects,
or when an attempt is made to use the SMTP instance before
connecting it to a server.
"""
class SMTPResponseException(SMTPException):
"""Base class for all exceptions that include an SMTP error code.
These exceptions are generated in some instances when the SMTP
server returns an error code. The error code is stored in the
`smtp_code' attribute of the error, and the `smtp_error' attribute
is set to the error message.
"""
def __init__(self, code, msg):
self.smtp_code = code
self.smtp_error = msg
self.args = (code, msg)
class SMTPSenderRefused(SMTPResponseException):
"""Sender address refused.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
In addition to the attributes set by on all SMTPResponseException
1999-11-28 13:11:06 -04:00
exceptions, this sets `sender' to the string that the SMTP refused.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
"""
def __init__(self, code, msg, sender):
self.smtp_code = code
self.smtp_error = msg
self.sender = sender
self.args = (code, msg, sender)
class SMTPRecipientsRefused(SMTPException):
1999-11-28 13:11:06 -04:00
"""All recipient addresses refused.
The errors for each recipient are accessible through the attribute
2001-01-14 21:36:40 -04:00
'recipients', which is a dictionary of exactly the same sort as
SMTP.sendmail() returns.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
"""
def __init__(self, recipients):
self.recipients = recipients
self.args = ( recipients,)
class SMTPDataError(SMTPResponseException):
"""The SMTP server didn't accept the data."""
class SMTPConnectError(SMTPResponseException):
1999-11-28 13:11:06 -04:00
"""Error during connection establishment."""
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
class SMTPHeloError(SMTPResponseException):
1999-11-28 13:11:06 -04:00
"""The server refused our HELO reply."""
class SMTPAuthenticationError(SMTPResponseException):
"""Authentication error.
Most probably the server didn't accept the username/password
combination provided.
"""
class SSLFakeSocket:
"""A fake socket object that really wraps a SSLObject.
2001-09-17 23:26:39 -03:00
It only supports what is needed in smtplib.
"""
def __init__(self, realsock, sslobj):
self.realsock = realsock
self.sslobj = sslobj
def send(self, str):
self.sslobj.write(str)
return len(str)
sendall = send
def close(self):
self.realsock.close()
class SSLFakeFile:
"""A fake file like object that really wraps a SSLObject.
2001-09-17 23:26:39 -03:00
It only supports what is needed in smtplib.
"""
Merge the rest of the trunk. Merged revisions 46490-46494,46496,46498,46500,46506,46521,46538,46558,46563-46567,46570-46571,46583,46593,46595-46598,46604,46606,46609-46753 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r46610 | martin.v.loewis | 2006-06-03 09:42:26 +0200 (Sat, 03 Jun 2006) | 2 lines Updated version (win32-icons2.zip) from #1490384. ........ r46612 | andrew.kuchling | 2006-06-03 20:09:41 +0200 (Sat, 03 Jun 2006) | 1 line [Bug #1472084] Fix description of do_tag ........ r46614 | andrew.kuchling | 2006-06-03 20:33:35 +0200 (Sat, 03 Jun 2006) | 1 line [Bug #1475554] Strengthen text to say 'must' instead of 'should' ........ r46616 | andrew.kuchling | 2006-06-03 20:41:28 +0200 (Sat, 03 Jun 2006) | 1 line [Bug #1441864] Clarify description of 'data' argument ........ r46617 | andrew.kuchling | 2006-06-03 20:43:24 +0200 (Sat, 03 Jun 2006) | 1 line Minor rewording ........ r46619 | andrew.kuchling | 2006-06-03 21:02:35 +0200 (Sat, 03 Jun 2006) | 9 lines [Bug #1497414] _self is a reserved word in the WATCOM 10.6 C compiler. Fix by renaming the variable. In a different module, Neal fixed it by renaming _self to self. There's already a variable named 'self' here, so I used selfptr. (I'm committing this on a Mac without Tk, but it's a simple search-and-replace. <crosses fingers>, so I'll watch the buildbots and see what happens.) ........ r46621 | fredrik.lundh | 2006-06-03 23:56:05 +0200 (Sat, 03 Jun 2006) | 5 lines "_self" is a said to be a reserved word in Watcom C 10.6. I'm not sure that's really standard compliant behaviour, but I guess we have to fix that anyway... ........ r46622 | andrew.kuchling | 2006-06-04 00:44:42 +0200 (Sun, 04 Jun 2006) | 1 line Update readme ........ r46623 | andrew.kuchling | 2006-06-04 00:59:23 +0200 (Sun, 04 Jun 2006) | 1 line Drop 0 parameter ........ r46624 | andrew.kuchling | 2006-06-04 00:59:59 +0200 (Sun, 04 Jun 2006) | 1 line Some code tidying; use curses.wrapper ........ r46625 | andrew.kuchling | 2006-06-04 01:02:15 +0200 (Sun, 04 Jun 2006) | 1 line Use True; value returned from main is unused ........ r46626 | andrew.kuchling | 2006-06-04 01:07:21 +0200 (Sun, 04 Jun 2006) | 1 line Use true division, and the True value ........ r46627 | andrew.kuchling | 2006-06-04 01:09:58 +0200 (Sun, 04 Jun 2006) | 1 line Docstring fix; use True ........ r46628 | andrew.kuchling | 2006-06-04 01:15:56 +0200 (Sun, 04 Jun 2006) | 1 line Put code in a main() function; loosen up the spacing to match current code style ........ r46629 | andrew.kuchling | 2006-06-04 01:39:07 +0200 (Sun, 04 Jun 2006) | 1 line Use functions; modernize code ........ r46630 | andrew.kuchling | 2006-06-04 01:43:22 +0200 (Sun, 04 Jun 2006) | 1 line This demo requires Medusa (not just asyncore); remove it ........ r46631 | andrew.kuchling | 2006-06-04 01:46:36 +0200 (Sun, 04 Jun 2006) | 2 lines Remove xmlrpc demo -- it duplicates the SimpleXMLRPCServer module. ........ r46632 | andrew.kuchling | 2006-06-04 01:47:22 +0200 (Sun, 04 Jun 2006) | 1 line Remove xmlrpc/ directory ........ r46633 | andrew.kuchling | 2006-06-04 01:51:21 +0200 (Sun, 04 Jun 2006) | 1 line Remove dangling reference ........ r46634 | andrew.kuchling | 2006-06-04 01:59:36 +0200 (Sun, 04 Jun 2006) | 1 line Add more whitespace; use a better socket name ........ r46635 | tim.peters | 2006-06-04 03:22:53 +0200 (Sun, 04 Jun 2006) | 2 lines Whitespace normalization. ........ r46637 | tim.peters | 2006-06-04 05:26:02 +0200 (Sun, 04 Jun 2006) | 16 lines In a PYMALLOC_DEBUG build obmalloc adds extra debugging info to each allocated block. This was using 4 bytes for each such piece of info regardless of platform. This didn't really matter before (proof: no bug reports, and the debug-build obmalloc would have assert-failed if it was ever asked for a chunk of memory >= 2**32 bytes), since container indices were plain ints. But after the Py_ssize_t changes, it's at least theoretically possible to allocate a list or string whose guts exceed 2**32 bytes, and the PYMALLOC_DEBUG routines would fail then (having only 4 bytes to record the originally requested size). Now we use sizeof(size_t) bytes for each of a PYMALLOC_DEBUG build's extra debugging fields. This won't make any difference on 32-bit boxes, but will add 16 bytes to each allocation in a debug build on a 64-bit box. ........ r46638 | tim.peters | 2006-06-04 05:38:04 +0200 (Sun, 04 Jun 2006) | 4 lines _PyObject_DebugMalloc(): The return value should add 2*sizeof(size_t) now, not 8. This probably accounts for current disasters on the 64-bit buildbot slaves. ........ r46639 | neal.norwitz | 2006-06-04 08:19:31 +0200 (Sun, 04 Jun 2006) | 1 line SF #1499797, Fix for memory leak in WindowsError_str ........ r46640 | andrew.macintyre | 2006-06-04 14:31:09 +0200 (Sun, 04 Jun 2006) | 2 lines Patch #1454481: Make thread stack size runtime tunable. ........ r46641 | andrew.macintyre | 2006-06-04 14:59:59 +0200 (Sun, 04 Jun 2006) | 2 lines clean up function declarations to conform to PEP-7 style. ........ r46642 | martin.blais | 2006-06-04 15:49:49 +0200 (Sun, 04 Jun 2006) | 15 lines Fixes in struct and socket from merge reviews. - Following Guido's comments, renamed * pack_to -> pack_into * recv_buf -> recv_into * recvfrom_buf -> recvfrom_into - Made fixes to _struct.c according to Neal Norwitz comments on the checkins list. - Converted some ints into the appropriate -- I hope -- ssize_t and size_t. ........ r46643 | ronald.oussoren | 2006-06-04 16:05:28 +0200 (Sun, 04 Jun 2006) | 3 lines "Import" LDFLAGS in Mac/OSX/Makefile.in to ensure pythonw gets build with the right compiler flags. ........ r46644 | ronald.oussoren | 2006-06-04 16:24:59 +0200 (Sun, 04 Jun 2006) | 2 lines Drop Mac wrappers for the WASTE library. ........ r46645 | tim.peters | 2006-06-04 17:49:07 +0200 (Sun, 04 Jun 2006) | 3 lines s_methods[]: Stop compiler warnings by casting s_unpack_from to PyCFunction. ........ r46646 | george.yoshida | 2006-06-04 19:04:12 +0200 (Sun, 04 Jun 2006) | 2 lines Remove a redundant word ........ r46647 | george.yoshida | 2006-06-04 19:17:25 +0200 (Sun, 04 Jun 2006) | 2 lines Markup fix ........ r46648 | martin.v.loewis | 2006-06-04 21:36:28 +0200 (Sun, 04 Jun 2006) | 2 lines Patch #1359618: Speed-up charmap encoder. ........ r46649 | georg.brandl | 2006-06-04 23:46:16 +0200 (Sun, 04 Jun 2006) | 3 lines Repair refleaks in unicodeobject. ........ r46650 | georg.brandl | 2006-06-04 23:56:52 +0200 (Sun, 04 Jun 2006) | 4 lines Patch #1346214: correctly optimize away "if 0"-style stmts (thanks to Neal for review) ........ r46651 | georg.brandl | 2006-06-05 00:15:37 +0200 (Mon, 05 Jun 2006) | 2 lines Bug #1500293: fix memory leaks in _subprocess module. ........ r46654 | tim.peters | 2006-06-05 01:43:53 +0200 (Mon, 05 Jun 2006) | 2 lines Whitespace normalization. ........ r46655 | tim.peters | 2006-06-05 01:52:47 +0200 (Mon, 05 Jun 2006) | 16 lines Revert revisions: 46640 Patch #1454481: Make thread stack size runtime tunable. 46647 Markup fix The first is causing many buildbots to fail test runs, and there are multiple causes with seemingly no immediate prospects for repairing them. See python-dev discussion. Note that a branch can (and should) be created for resolving these problems, like svn copy svn+ssh://svn.python.org/python/trunk -r46640 svn+ssh://svn.python.org/python/branches/NEW_BRANCH followed by merging rev 46647 to the new branch. ........ r46656 | andrew.kuchling | 2006-06-05 02:08:09 +0200 (Mon, 05 Jun 2006) | 1 line Mention second encoding speedup ........ r46657 | gregory.p.smith | 2006-06-05 02:31:01 +0200 (Mon, 05 Jun 2006) | 7 lines bugfix: when log_archive was called with the DB_ARCH_REMOVE flag present in BerkeleyDB >= 4.2 it tried to construct a list out of an uninitialized char **log_list. feature: export the DB_ARCH_REMOVE flag by name in the module on BerkeleyDB >= 4.2. ........ r46658 | gregory.p.smith | 2006-06-05 02:33:35 +0200 (Mon, 05 Jun 2006) | 5 lines fix a bug in the previous commit. don't leak empty list on error return and fix the additional rare (out of memory only) bug that it was supposed to fix of not freeing log_list when the python allocator failed. ........ r46660 | tim.peters | 2006-06-05 02:55:26 +0200 (Mon, 05 Jun 2006) | 9 lines "Flat is better than nested." Move the long-winded, multiply-nested -R support out of runtest() and into some module-level helper functions. This makes runtest() and the -R code easier to follow. That in turn allowed seeing some opportunities for code simplification, and made it obvious that reglog.txt never got closed. ........ r46661 | hyeshik.chang | 2006-06-05 02:59:54 +0200 (Mon, 05 Jun 2006) | 3 lines Fix a potentially invalid memory access of CJKCodecs' shift-jis decoder. (found by Neal Norwitz) ........ r46663 | gregory.p.smith | 2006-06-05 03:39:52 +0200 (Mon, 05 Jun 2006) | 3 lines * support DBEnv.log_stat() method on BerkeleyDB >= 4.0 [patch #1494885] ........ r46664 | tim.peters | 2006-06-05 03:43:03 +0200 (Mon, 05 Jun 2006) | 3 lines Remove doctest.testmod's deprecated (in 2.4) `isprivate` argument. A lot of hair went into supporting that! ........ r46665 | tim.peters | 2006-06-05 03:47:24 +0200 (Mon, 05 Jun 2006) | 2 lines Whitespace normalization. ........ r46666 | tim.peters | 2006-06-05 03:48:21 +0200 (Mon, 05 Jun 2006) | 2 lines Make doctest news more accurate. ........ r46667 | gregory.p.smith | 2006-06-05 03:56:15 +0200 (Mon, 05 Jun 2006) | 3 lines * support DBEnv.lsn_reset() method on BerkeleyDB >= 4.4 [patch #1494902] ........ r46668 | gregory.p.smith | 2006-06-05 04:02:25 +0200 (Mon, 05 Jun 2006) | 3 lines mention the just committed bsddb changes ........ r46671 | gregory.p.smith | 2006-06-05 19:38:04 +0200 (Mon, 05 Jun 2006) | 3 lines * add support for DBSequence objects [patch #1466734] ........ r46672 | gregory.p.smith | 2006-06-05 20:20:07 +0200 (Mon, 05 Jun 2006) | 3 lines forgot to add this file in previous commit ........ r46673 | tim.peters | 2006-06-05 20:36:12 +0200 (Mon, 05 Jun 2006) | 2 lines Whitespace normalization. ........ r46674 | tim.peters | 2006-06-05 20:36:54 +0200 (Mon, 05 Jun 2006) | 2 lines Add missing svn:eol-style property to text files. ........ r46675 | gregory.p.smith | 2006-06-05 20:48:21 +0200 (Mon, 05 Jun 2006) | 4 lines * fix DBCursor.pget() bug with keyword argument names when no data= is supplied [SF pybsddb bug #1477863] ........ r46676 | andrew.kuchling | 2006-06-05 21:05:32 +0200 (Mon, 05 Jun 2006) | 1 line Remove use of Trove name, which isn't very helpful to users ........ r46677 | andrew.kuchling | 2006-06-05 21:08:25 +0200 (Mon, 05 Jun 2006) | 1 line [Bug #1470026] Include link to list of classifiers ........ r46679 | tim.peters | 2006-06-05 22:48:49 +0200 (Mon, 05 Jun 2006) | 10 lines Access _struct attributes directly instead of mucking with getattr. string_reverse(): Simplify. assertRaises(): Raise TestFailed on failure. test_unpack_from(), test_pack_into(), test_pack_into_fn(): never use `assert` to test for an expected result (it doesn't test anything when Python is run with -O). ........ r46680 | tim.peters | 2006-06-05 22:49:27 +0200 (Mon, 05 Jun 2006) | 2 lines Add missing svn:eol-style property to text files. ........ r46681 | gregory.p.smith | 2006-06-06 01:38:06 +0200 (Tue, 06 Jun 2006) | 3 lines add depends = ['md5.h'] to the _md5 module extension for correctness sake. ........ r46682 | brett.cannon | 2006-06-06 01:51:55 +0200 (Tue, 06 Jun 2006) | 4 lines Add 3 more bytes to a buffer to cover constants in string and null byte on top of 10 possible digits for an int. Closes bug #1501223. ........ r46684 | gregory.p.smith | 2006-06-06 01:59:37 +0200 (Tue, 06 Jun 2006) | 5 lines - bsddb: the __len__ method of a DB object has been fixed to return correct results. It could previously incorrectly return 0 in some cases. Fixes SF bug 1493322 (pybsddb bug 1184012). ........ r46686 | tim.peters | 2006-06-06 02:25:07 +0200 (Tue, 06 Jun 2006) | 7 lines _PySys_Init(): It's rarely a good idea to size a buffer to the exact maximum size someone guesses is needed. In this case, if we're really worried about extreme integers, then "cp%d" can actually need 14 bytes (2 for "cp" + 1 for \0 at the end + 11 for -(2**31-1)). So reserve 128 bytes instead -- nothing is actually saved by making a stack-local buffer tiny. ........ r46687 | neal.norwitz | 2006-06-06 09:22:08 +0200 (Tue, 06 Jun 2006) | 1 line Remove unused variable (and stop compiler warning) ........ r46688 | neal.norwitz | 2006-06-06 09:23:01 +0200 (Tue, 06 Jun 2006) | 1 line Fix a bunch of parameter strings ........ r46689 | thomas.heller | 2006-06-06 13:34:33 +0200 (Tue, 06 Jun 2006) | 6 lines Convert CFieldObject tp_members to tp_getset, since there is no structmember typecode for Py_ssize_t fields. This should fix some of the errors on the PPC64 debian machine (64-bit, big endian). Assigning to readonly fields now raises AttributeError instead of TypeError, so the testcase has to be changed as well. ........ r46690 | thomas.heller | 2006-06-06 13:54:32 +0200 (Tue, 06 Jun 2006) | 1 line Damn - the sentinel was missing. And fix another silly mistake. ........ r46691 | martin.blais | 2006-06-06 14:46:55 +0200 (Tue, 06 Jun 2006) | 13 lines Normalized a few cases of whitespace in function declarations. Found them using:: find . -name '*.py' | while read i ; do grep 'def[^(]*( ' $i /dev/null ; done find . -name '*.py' | while read i ; do grep ' ):' $i /dev/null ; done (I was doing this all over my own code anyway, because I'd been using spaces in all defs, so I thought I'd make a run on the Python code as well. If you need to do such fixes in your own code, you can use xx-rename or parenregu.el within emacs.) ........ r46693 | thomas.heller | 2006-06-06 17:34:18 +0200 (Tue, 06 Jun 2006) | 1 line Specify argtypes for all test functions. Maybe that helps on strange ;-) architectures ........ r46694 | tim.peters | 2006-06-06 17:50:17 +0200 (Tue, 06 Jun 2006) | 5 lines BSequence_set_range(): Rev 46688 ("Fix a bunch of parameter strings") changed this function's signature seemingly by mistake, which is causing buildbots to fail test_bsddb3. Restored the pre-46688 signature. ........ r46695 | tim.peters | 2006-06-06 17:52:35 +0200 (Tue, 06 Jun 2006) | 4 lines On python-dev Thomas Heller said these were committed by mistake in rev 46693, so reverting this part of rev 46693. ........ r46696 | andrew.kuchling | 2006-06-06 19:10:41 +0200 (Tue, 06 Jun 2006) | 1 line Fix comment typo ........ r46697 | brett.cannon | 2006-06-06 20:08:16 +0200 (Tue, 06 Jun 2006) | 2 lines Fix coding style guide bug. ........ r46698 | thomas.heller | 2006-06-06 20:50:46 +0200 (Tue, 06 Jun 2006) | 2 lines Add a hack so that foreign functions returning float now do work on 64-bit big endian platforms. ........ r46699 | thomas.heller | 2006-06-06 21:25:13 +0200 (Tue, 06 Jun 2006) | 3 lines Use the same big-endian hack as in _ctypes/callproc.c for callback functions. This fixes the callback function tests that return float. ........ r46700 | ronald.oussoren | 2006-06-06 21:50:24 +0200 (Tue, 06 Jun 2006) | 5 lines * Ensure that "make altinstall" works when the tree was configured with --enable-framework * Also for --enable-framework: allow users to use --prefix to specify the location of the compatibility symlinks (such as /usr/local/bin/python) ........ r46701 | ronald.oussoren | 2006-06-06 21:56:00 +0200 (Tue, 06 Jun 2006) | 3 lines A quick hack to ensure the right key-bindings for IDLE on osx: install patched configuration files during a framework install. ........ r46702 | tim.peters | 2006-06-07 03:04:59 +0200 (Wed, 07 Jun 2006) | 4 lines dash_R_cleanup(): Clear filecmp._cache. This accounts for different results across -R runs (at least on Windows) of test_filecmp. ........ r46705 | tim.peters | 2006-06-07 08:57:51 +0200 (Wed, 07 Jun 2006) | 17 lines SF patch 1501987: Remove randomness from test_exceptions, from ?iga Seilnacht (sorry about the name, but Firefox on my box can't display the first character of the name -- the SF "Unix name" is zseil). This appears to cure the oddball intermittent leaks across runs when running test_exceptions under -R. I'm not sure why, but I'm too sleepy to care ;-) The thrust of the SF patch was to remove randomness in the pickle protocol used. I changed the patch to use range(pickle.HIGHEST_PROTOCOL + 1), to try both pickle and cPickle, and randomly mucked with other test lines to put statements on their own lines. Not a bugfix candidate (this is fiddling new-in-2.5 code). ........ r46706 | andrew.kuchling | 2006-06-07 15:55:33 +0200 (Wed, 07 Jun 2006) | 1 line Add an SQLite introduction, taken from the 'What's New' text ........ r46708 | andrew.kuchling | 2006-06-07 19:02:52 +0200 (Wed, 07 Jun 2006) | 1 line Mention other placeholders ........ r46709 | andrew.kuchling | 2006-06-07 19:03:46 +0200 (Wed, 07 Jun 2006) | 1 line Add an item; also, escape % ........ r46710 | andrew.kuchling | 2006-06-07 19:04:01 +0200 (Wed, 07 Jun 2006) | 1 line Mention other placeholders ........ r46716 | ronald.oussoren | 2006-06-07 20:57:44 +0200 (Wed, 07 Jun 2006) | 2 lines Move Mac/OSX/Tools one level up ........ r46717 | ronald.oussoren | 2006-06-07 20:58:01 +0200 (Wed, 07 Jun 2006) | 2 lines Move Mac/OSX/PythonLauncher one level up ........ r46718 | ronald.oussoren | 2006-06-07 20:58:42 +0200 (Wed, 07 Jun 2006) | 2 lines mv Mac/OSX/BuildScript one level up ........ r46719 | ronald.oussoren | 2006-06-07 21:02:03 +0200 (Wed, 07 Jun 2006) | 2 lines Move Mac/OSX/* one level up ........ r46720 | ronald.oussoren | 2006-06-07 21:06:01 +0200 (Wed, 07 Jun 2006) | 2 lines And the last bit: move IDLE one level up and adjust makefiles ........ r46723 | ronald.oussoren | 2006-06-07 21:38:53 +0200 (Wed, 07 Jun 2006) | 4 lines - Patch the correct version of python in the Info.plists at build time, instead of relying on a maintainer to update them before releases. - Remove the now empty Mac/OSX directory ........ r46727 | ronald.oussoren | 2006-06-07 22:18:44 +0200 (Wed, 07 Jun 2006) | 7 lines * If BuildApplet.py is used as an applet it starts with a version of sys.exutable that isn't usuable on an #!-line. That results in generated applets that don't actually work. Work around this problem by resetting sys.executable. * argvemulator.py didn't work on intel macs. This patch fixes this (bug #1491468) ........ r46728 | tim.peters | 2006-06-07 22:40:06 +0200 (Wed, 07 Jun 2006) | 2 lines Whitespace normalization. ........ r46729 | tim.peters | 2006-06-07 22:40:54 +0200 (Wed, 07 Jun 2006) | 2 lines Add missing svn:eol-style property to text files. ........ r46730 | thomas.heller | 2006-06-07 22:43:06 +0200 (Wed, 07 Jun 2006) | 7 lines Fix for foreign functions returning small structures on 64-bit big endian machines. Should fix the remaininf failure in the PPC64 Debian buildbot. Thanks to Matthias Klose for providing access to a machine to debug and test this. ........ r46731 | brett.cannon | 2006-06-07 23:48:17 +0200 (Wed, 07 Jun 2006) | 2 lines Clarify documentation for bf_getcharbuffer. ........ r46735 | neal.norwitz | 2006-06-08 07:12:45 +0200 (Thu, 08 Jun 2006) | 1 line Fix a refleak in recvfrom_into ........ r46736 | gregory.p.smith | 2006-06-08 07:17:08 +0200 (Thu, 08 Jun 2006) | 9 lines - bsddb: the bsddb.dbtables Modify method now raises the proper error and aborts the db transaction safely when a modifier callback fails. Fixes SF python patch/bug #1408584. Also cleans up the bsddb.dbtables docstrings since thats the only documentation that exists for that unadvertised module. (people really should really just use sqlite3) ........ r46737 | gregory.p.smith | 2006-06-08 07:38:11 +0200 (Thu, 08 Jun 2006) | 4 lines * Turn the deadlock situation described in SF bug #775414 into a DBDeadLockError exception. * add the test case for my previous dbtables commit. ........ r46738 | gregory.p.smith | 2006-06-08 07:39:54 +0200 (Thu, 08 Jun 2006) | 2 lines pasted set_lk_detect line in wrong spot in previous commit. fixed. passes tests this time. ........ r46739 | armin.rigo | 2006-06-08 12:56:24 +0200 (Thu, 08 Jun 2006) | 6 lines (arre, arigo) SF bug #1350060 Give a consistent behavior for comparison and hashing of method objects (both user- and built-in methods). Now compares the 'self' recursively. The hash was already asking for the hash of 'self'. ........ r46740 | andrew.kuchling | 2006-06-08 13:56:44 +0200 (Thu, 08 Jun 2006) | 1 line Typo fix ........ r46741 | georg.brandl | 2006-06-08 14:45:01 +0200 (Thu, 08 Jun 2006) | 2 lines Bug #1502750: Fix getargs "i" format to use LONG_MIN and LONG_MAX for bounds checking. ........ r46743 | georg.brandl | 2006-06-08 14:54:13 +0200 (Thu, 08 Jun 2006) | 2 lines Bug #1502728: Correctly link against librt library on HP-UX. ........ r46745 | georg.brandl | 2006-06-08 14:55:47 +0200 (Thu, 08 Jun 2006) | 3 lines Add news for recent bugfix. ........ r46746 | georg.brandl | 2006-06-08 15:31:07 +0200 (Thu, 08 Jun 2006) | 4 lines Argh. "integer" is a very confusing word ;) Actually, checking for INT_MAX and INT_MIN is correct since the format code explicitly handles a C "int". ........ r46748 | nick.coghlan | 2006-06-08 15:54:49 +0200 (Thu, 08 Jun 2006) | 1 line Add functools.update_wrapper() and functools.wraps() as described in PEP 356 ........ r46751 | georg.brandl | 2006-06-08 16:50:21 +0200 (Thu, 08 Jun 2006) | 4 lines Bug #1502805: don't alias file.__exit__ to file.close since the latter can return something that's true. ........ r46752 | georg.brandl | 2006-06-08 16:50:53 +0200 (Thu, 08 Jun 2006) | 3 lines Convert test_file to unittest. ........
2006-06-08 12:35:45 -03:00
def __init__(self, sslobj):
self.sslobj = sslobj
def readline(self):
str = ""
chr = None
while chr != "\n":
chr = self.sslobj.read(1)
str += chr
return str
def close(self):
pass
def quoteaddr(addr):
"""Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything rfc822.parseaddr can handle.
"""
m = (None, None)
try:
m = email.Utils.parseaddr(addr)[1]
except AttributeError:
pass
if m == (None, None): # Indicates parse failure or AttributeError
# something weird here.. punt -ddm
return "<%s>" % addr
elif m is None:
# the sender wants an empty return address
return "<>"
else:
return "<%s>" % m
def quotedata(data):
"""Quote data for email.
1999-11-28 13:11:06 -04:00
Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Internet CRLF end-of-line.
"""
return re.sub(r'(?m)^\.', '..',
re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
class SMTP:
"""This class manages a connection to an SMTP or ESMTP server.
SMTP Objects:
2001-01-14 21:36:40 -04:00
SMTP objects have the following attributes:
helo_resp
This is the message given by the server in response to the
most recent HELO command.
2001-01-14 21:36:40 -04:00
ehlo_resp
2001-01-14 21:36:40 -04:00
This is the message given by the server in response to the
most recent EHLO command. This is usually multiline.
2001-01-14 21:36:40 -04:00
does_esmtp
This is a True value _after you do an EHLO command_, if the
server supports ESMTP.
2001-01-14 21:36:40 -04:00
esmtp_features
This is a dictionary, which, if the server supports ESMTP,
1999-11-28 13:11:06 -04:00
will _after you do an EHLO command_, contain the names of the
SMTP service extensions this server supports, and their
parameters (if any).
1999-11-28 13:11:06 -04:00
2001-01-14 21:36:40 -04:00
Note, all extension names are mapped to lower case in the
dictionary.
1999-11-28 13:11:06 -04:00
See each method's docstrings for details. In general, there is a
method of the same name to perform each SMTP command. There is also a
method called 'sendmail' that will do an entire mail transaction.
"""
debuglevel = 0
file = None
helo_resp = None
ehlo_resp = None
does_esmtp = 0
def __init__(self, host = '', port = 0, local_hostname = None):
"""Initialize a new instance.
If specified, `host' is the name of the remote host to which to
connect. If specified, `port' specifies the port to which to connect.
1999-11-28 13:11:06 -04:00
By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
if the specified `host' doesn't respond correctly. If specified,
2002-04-15 22:38:40 -03:00
`local_hostname` is used as the FQDN of the local host. By default,
the local hostname is found using socket.getfqdn().
"""
self.esmtp_features = {}
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
if host:
(code, msg) = self.connect(host, port)
if code != 220:
raise SMTPConnectError(code, msg)
2002-06-01 21:40:05 -03:00
if local_hostname is not None:
self.local_hostname = local_hostname
else:
# RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
# if that can't be calculated, that we should use a domain literal
# instead (essentially an encoded IP address like [A.B.C.D]).
fqdn = socket.getfqdn()
if '.' in fqdn:
self.local_hostname = fqdn
else:
# We can't find an fqdn hostname, so use a domain literal
addr = '127.0.0.1'
try:
addr = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
pass
self.local_hostname = '[%s]' % addr
2001-01-14 21:36:40 -04:00
def set_debuglevel(self, debuglevel):
"""Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server.
"""
self.debuglevel = debuglevel
def connect(self, host='localhost', port = 0):
"""Connect to a host on a given port.
If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.
Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.
"""
2001-07-26 10:37:33 -03:00
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i+1:]
2001-02-09 01:40:38 -04:00
try: port = int(port)
except ValueError:
raise socket.error, "nonnumeric port"
if not port: port = SMTP_PORT
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
self.sock = None
2001-07-26 10:37:33 -03:00
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0: print>>stderr, 'connect:', sa
2001-07-26 10:37:33 -03:00
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0: print>>stderr, 'connect fail:', msg
if self.sock:
self.sock.close()
2001-07-26 10:37:33 -03:00
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
(code, msg) = self.getreply()
if self.debuglevel > 0: print>>stderr, "connect:", msg
return (code, msg)
2001-01-14 21:36:40 -04:00
def send(self, str):
"""Send `str' to the server."""
if self.debuglevel > 0: print>>stderr, 'send:', repr(str)
if self.sock:
try:
self.sock.sendall(str)
except socket.error:
self.close()
raise SMTPServerDisconnected('Server not connected')
else:
raise SMTPServerDisconnected('please run connect() first')
2001-01-14 21:36:40 -04:00
def putcmd(self, cmd, args=""):
"""Send a command to the server."""
if args == "":
str = '%s%s' % (cmd, CRLF)
else:
str = '%s %s%s' % (cmd, args, CRLF)
self.send(str)
2001-01-14 21:36:40 -04:00
def getreply(self):
"""Get a reply from the server.
2001-01-14 21:36:40 -04:00
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
resp=[]
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
if self.file is None:
self.file = self.sock.makefile('rb')
while 1:
line = self.file.readline()
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed")
if self.debuglevel > 0: print>>stderr, 'reply:', repr(line)
2001-02-09 01:40:38 -04:00
resp.append(line[4:].strip())
code=line[:3]
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
# Check that the error code is syntactically correct.
# Don't attempt to read a continuation line if it is broken.
try:
2001-02-09 01:40:38 -04:00
errcode = int(code)
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
except ValueError:
errcode = -1
break
# Check if multiline response.
if line[3:4]!="-":
break
2001-02-09 01:40:38 -04:00
errmsg = "\n".join(resp)
2001-01-14 21:36:40 -04:00
if self.debuglevel > 0:
print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
return errcode, errmsg
2001-01-14 21:36:40 -04:00
def docmd(self, cmd, args=""):
"""Send a command, and return its response code."""
self.putcmd(cmd,args)
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return self.getreply()
# std smtp commands
def helo(self, name=''):
"""SMTP 'helo' command.
Hostname to send for this command defaults to the FQDN of the local
host.
"""
self.putcmd("helo", name or self.local_hostname)
(code,msg)=self.getreply()
self.helo_resp=msg
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return (code,msg)
def ehlo(self, name=''):
""" SMTP 'ehlo' command.
Hostname to send for this command defaults to the FQDN of the local
host.
"""
self.esmtp_features = {}
self.putcmd("ehlo", name or self.local_hostname)
(code,msg)=self.getreply()
2001-01-14 21:36:40 -04:00
# According to RFC1869 some (badly written)
# MTA's will disconnect on an ehlo. Toss an exception if
# that happens -ddm
if code == -1 and len(msg) == 0:
self.close()
raise SMTPServerDisconnected("Server not connected")
self.ehlo_resp=msg
if code != 250:
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return (code,msg)
self.does_esmtp=1
#parse the ehlo response -ddm
2001-02-09 01:40:38 -04:00
resp=self.ehlo_resp.split('\n')
del resp[0]
for each in resp:
2002-07-26 21:38:30 -03:00
# To be able to communicate with as many SMTP servers as possible,
# we have to take the old-style auth advertisement into account,
# because:
# 1) Else our SMTP feature parser gets confused.
# 2) There are some servers that only advertise the auth methods we
# support using the old style.
auth_match = OLDSTYLE_AUTH.match(each)
if auth_match:
# This doesn't remove duplicates, but that's no problem
self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \
+ " " + auth_match.groups(0)[0]
continue
# RFC 1869 requires a space between ehlo keyword and parameters.
# It's actually stricter, in that only spaces are allowed between
# parameters, but were not going to check for that here. Note
# that the space isn't present if there are no parameters.
m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?',each)
if m:
2001-02-09 01:40:38 -04:00
feature=m.group("feature").lower()
params=m.string[m.end("feature"):].strip()
2002-07-26 21:38:30 -03:00
if feature == "auth":
self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
+ " " + params
else:
self.esmtp_features[feature]=params
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return (code,msg)
def has_extn(self, opt):
"""Does the server support a given SMTP service extension?"""
return opt.lower() in self.esmtp_features
1998-04-03 13:03:13 -04:00
def help(self, args=''):
"""SMTP 'help' command.
Returns help text from server."""
1998-04-03 13:03:13 -04:00
self.putcmd("help", args)
return self.getreply()[1]
def rset(self):
"""SMTP 'rset' command -- resets session."""
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return self.docmd("rset")
def noop(self):
"""SMTP 'noop' command -- doesn't do anything :>"""
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return self.docmd("noop")
def mail(self,sender,options=[]):
"""SMTP 'mail' command -- begins mail xfer session."""
optionlist = ''
if options and self.does_esmtp:
2001-02-09 01:40:38 -04:00
optionlist = ' ' + ' '.join(options)
self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
return self.getreply()
def rcpt(self,recip,options=[]):
"""SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
optionlist = ''
if options and self.does_esmtp:
2001-02-09 01:40:38 -04:00
optionlist = ' ' + ' '.join(options)
self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
return self.getreply()
def data(self,msg):
2001-01-14 21:36:40 -04:00
"""SMTP 'DATA' command -- sends message data to server.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
Automatically quotes lines beginning with a period per rfc821.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
Raises SMTPDataError if there is an unexpected reply to the
DATA command; the return value from this method is the final
response code received when the all data is sent.
"""
self.putcmd("data")
(code,repl)=self.getreply()
if self.debuglevel >0 : print>>stderr, "data:", (code,repl)
if code != 354:
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
raise SMTPDataError(code,repl)
else:
q = quotedata(msg)
if q[-2:] != CRLF:
q = q + CRLF
q = q + "." + CRLF
self.send(q)
(code,msg)=self.getreply()
if self.debuglevel >0 : print>>stderr, "data:", (code,msg)
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
return (code,msg)
def verify(self, address):
"""SMTP 'verify' command -- checks for address validity."""
self.putcmd("vrfy", quoteaddr(address))
return self.getreply()
# a.k.a.
vrfy=verify
def expn(self, address):
"""SMTP 'verify' command -- checks for address validity."""
self.putcmd("expn", quoteaddr(address))
return self.getreply()
# some useful methods
def login(self, user, password):
"""Log in on an SMTP server that requires authentication.
The arguments are:
- user: The user name to authenticate with.
- password: The password for the authentication.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method will return normally if the authentication was successful.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
SMTPAuthenticationError The server didn't accept the username/
password combination.
SMTPException No suitable authentication method was
found.
"""
def encode_cram_md5(challenge, user, password):
challenge = base64.decodestring(challenge)
response = user + " " + hmac.HMAC(password, challenge).hexdigest()
2002-07-26 21:38:30 -03:00
return encode_base64(response, eol="")
def encode_plain(user, password):
return encode_base64("\0%s\0%s" % (user, password), eol="")
2002-08-08 17:19:19 -03:00
AUTH_PLAIN = "PLAIN"
AUTH_CRAM_MD5 = "CRAM-MD5"
2002-07-26 21:38:30 -03:00
AUTH_LOGIN = "LOGIN"
if self.helo_resp is None and self.ehlo_resp is None:
if not (200 <= self.ehlo()[0] <= 299):
(code, resp) = self.helo()
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
if not self.has_extn("auth"):
raise SMTPException("SMTP AUTH extension not supported by server.")
# Authentication methods the server supports:
authlist = self.esmtp_features["auth"].split()
# List of authentication methods we support: from preferred to
# less preferred methods. Except for the purpose of testing the weaker
# ones, we prefer stronger methods like CRAM-MD5:
2002-07-26 21:38:30 -03:00
preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
# Determine the authentication method we'll use
authmethod = None
for method in preferred_auths:
if method in authlist:
authmethod = method
break
2001-09-17 23:26:39 -03:00
if authmethod == AUTH_CRAM_MD5:
(code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
if code == 503:
# 503 == 'Error: already authenticated'
return (code, resp)
(code, resp) = self.docmd(encode_cram_md5(resp, user, password))
elif authmethod == AUTH_PLAIN:
2001-09-17 23:26:39 -03:00
(code, resp) = self.docmd("AUTH",
AUTH_PLAIN + " " + encode_plain(user, password))
2002-07-26 21:38:30 -03:00
elif authmethod == AUTH_LOGIN:
(code, resp) = self.docmd("AUTH",
"%s %s" % (AUTH_LOGIN, encode_base64(user, eol="")))
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = self.docmd(encode_base64(password, eol=""))
2002-05-31 14:49:10 -03:00
elif authmethod is None:
raise SMTPException("No suitable authentication method found.")
if code not in (235, 503):
# 235 == 'Authentication successful'
# 503 == 'Error: already authenticated'
raise SMTPAuthenticationError(code, resp)
return (code, resp)
def starttls(self, keyfile = None, certfile = None):
"""Puts the connection to the SMTP server into TLS mode.
2001-09-17 23:26:39 -03:00
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
"""
2001-09-17 23:26:39 -03:00
(resp, reply) = self.docmd("STARTTLS")
if resp == 220:
sslobj = socket.ssl(self.sock, keyfile, certfile)
self.sock = SSLFakeSocket(self.sock, sslobj)
self.file = SSLFakeFile(sslobj)
return (resp, reply)
2001-09-17 23:26:39 -03:00
def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
2001-01-14 21:36:40 -04:00
rcpt_options=[]):
"""This command performs an entire mail transaction.
2001-01-14 21:36:40 -04:00
The arguments are:
- from_addr : The address sending this mail.
- to_addrs : A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
2001-01-14 21:36:40 -04:00
- msg : The message to send.
- mail_options : List of ESMTP options (such as 8bitmime) for the
mail command.
- rcpt_options : List of ESMTP options (such as DSN commands) for
all the rcpt commands.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first. If the server does ESMTP, message size
and each of the specified options will be passed to it. If EHLO
fails, HELO will be tried and ESMTP options suppressed.
This method will return normally if the mail is accepted for at least
1999-11-28 13:11:06 -04:00
one recipient. It returns a dictionary, with one entry for each
recipient that was refused. Each entry contains a tuple of the SMTP
error code and the accompanying error message sent by the server.
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
2001-01-14 21:36:40 -04:00
the helo greeting.
1999-11-28 13:11:06 -04:00
SMTPRecipientsRefused The server rejected ALL recipients
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
(no mail was sent).
SMTPSenderRefused The server didn't accept the from_addr.
SMTPDataError The server replied with an unexpected
error code (other than a refusal of
a recipient).
Note: the connection will be open even after an exception is raised.
Example:
2001-01-14 21:36:40 -04:00
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
>>> msg = '''\\
... From: Me@my.org
... Subject: testin'...
...
... This is a test '''
>>> s.sendmail("me@my.org",tolist,msg)
{ "three@three.org" : ( 550 ,"User unknown" ) }
>>> s.quit()
2001-01-14 21:36:40 -04:00
In the above example, the message was accepted for delivery to three
of the four addresses, and one was rejected, with the error code
1999-11-28 13:11:06 -04:00
550. If all addresses are accepted, then the method will return an
empty dictionary.
"""
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
if self.helo_resp is None and self.ehlo_resp is None:
if not (200 <= self.ehlo()[0] <= 299):
(code,resp) = self.helo()
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
esmtp_opts = []
if self.does_esmtp:
# Hmmm? what's this? -ddm
# self.esmtp_features['7bit']=""
if self.has_extn('size'):
esmtp_opts.append("size=%d" % len(msg))
for option in mail_options:
esmtp_opts.append(option)
(code,resp) = self.mail(from_addr, esmtp_opts)
if code != 250:
self.rset()
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
raise SMTPSenderRefused(code, resp, from_addr)
senderrs={}
if isinstance(to_addrs, basestring):
to_addrs = [to_addrs]
for each in to_addrs:
(code,resp)=self.rcpt(each, rcpt_options)
if (code != 250) and (code != 251):
senderrs[each]=(code,resp)
if len(senderrs)==len(to_addrs):
# the server refused all our recipients
self.rset()
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
raise SMTPRecipientsRefused(senderrs)
(code,resp) = self.data(msg)
if code != 250:
self.rset()
Changes by Per Cederquist and The Dragon. Per writes: """ The application where Signum Support uses smtplib needs to be able to report good error messages to the user when sending email fails. To help in diagnosing problems it is useful to be able to report the entire message sent by the server, not only the SMTP error code of the offending command. A lot of the functions in sendmail.py unfortunately discards the message, leaving only the code. The enclosed patch fixes that problem. The enclosed patch also introduces a base class for exceptions that include an SMTP error code and error message, and make the code and message available on separate attributes, so that surrounding code can deal with them in whatever way it sees fit. I've also added some documentation to the exception classes. The constructor will now raise an exception if it cannot connect to the SMTP server. The data() method will raise an SMTPDataError if it doesn't receive the expected 354 code in the middle of the exchange. According to section 5.2.10 of RFC 1123 a smtp client must accept "any text, including no text at all" after the error code. If the response of a HELO command contains no text self.helo_resp will be set to the empty string (""). The patch fixes the test in the sendmail() method so that helo_resp is tested against None; if it has the empty string as value the sendmail() method would invoke the helo() method again. The code no longer accepts a -1 reply from the ehlo() method in sendmail(). [Text about removing SMTPRecipientsRefused deleted --GvR] """ and also: """ smtplib.py appends an extra blank line to the outgoing mail if the `msg' argument to the sendmail method already contains a trailing newline. This patch should fix the problem. """ The Dragon writes: """ Mostly I just re-added the SMTPRecipientsRefused exception (the exeption object now has the appropriate info in it ) [Per had removed this in his patch --GvR] and tweaked the behavior of the sendmail method whence it throws the newly added SMTPHeloException (it was closing the connection, which it shouldn't. whatever catches the exception should do that. ) I pondered the change of the return values to tuples all around, and after some thinking I decided that regularizing the return values was too much of the Right Thing (tm) to not do. My one concern is that code expecting an integer & getting a tuple may fail silently. (i.e. if it's doing : x.somemethod() >= 400: expecting an integer, the expression will always be true if it gets a tuple instead. ) However, most smtplib code I've seen only really uses the sendmail() method, so this wouldn't bother it. Usually code I've seen that calls the other methods usually only calls helo() and ehlo() for doing ESMTP, a feature which was not in the smtplib included with 1.5.1, and thus I would think not much code uses it yet. """
1999-04-07 12:03:39 -03:00
raise SMTPDataError(code, resp)
#if we got here then somebody got our mail
2001-01-14 21:36:40 -04:00
return senderrs
def close(self):
"""Close the connection to the SMTP server."""
if self.file:
self.file.close()
self.file = None
if self.sock:
self.sock.close()
self.sock = None
def quit(self):
"""Terminate the SMTP session."""
self.docmd("quit")
self.close()
# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost.
if __name__ == '__main__':
2001-08-13 11:41:39 -03:00
import sys
def prompt(prompt):
sys.stdout.write(prompt + ": ")
2001-02-09 01:40:38 -04:00
return sys.stdin.readline().strip()
fromaddr = prompt("From")
2001-02-09 03:40:17 -04:00
toaddrs = prompt("To").split(',')
print "Enter message, end with ^D:"
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
print "Message length is %d" % len(msg)
server = SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()