Foundations of Python Network Programming

(WallPaper) #1
Chapter 13 ■ SMtp

253

try:
connection = smtplib.SMTP(server)
report_on_message_size(connection, fromaddr, toaddrs, message)
except (socket.gaierror, socket.error, socket.herror,
smtplib.SMTPException) as e:
print("Your message may not have been sent!")
print(e)
sys.exit(1)
else:
s = '' if len(toaddrs) == 1 else 's'
print("Message sent to {} recipient{}".format(len(toaddrs), s))
connection.quit()


def report_on_message_size(connection, fromaddr, toaddrs, message):
code = connection.ehlo()[0]
uses_esmtp = (200 <= code <= 299)
if not uses_esmtp:
code = connection.helo()[0]
if not (200 <= code <= 299):
print("Remote server refused HELO; code:", code)
sys.exit(1)


if uses_esmtp and connection.has_extn('size'):
print("Maximum message size is", connection.esmtp_features['size'])
if len(message) > int(connection.esmtp_features['size']):
print("Message too large; aborting.")
sys.exit(1)


connection.sendmail(fromaddr, toaddrs, message)


if name == 'main':
main()


If you run this program, and the remote server provides its maximum message size, then the program will display
the size on your screen and verify that its message does not exceed that size before sending. (For a tiny message like
this, the check is rather silly, but the listing illustrates the pattern you can use successfully with much larger messages.)
Here is what running this program might look like:


$ python3 ehlo.py mail.example.com [email protected] [email protected]
Maximum message size is 33554432
Message successfully sent to 1 recipient


Take a look at the part of the code that verifies the result from a call to ehlo() or helo(). Those two functions
return a list; the first item in the list is a numeric result code from the remote SMTP server. Results between 200 and
299, inclusive, indicate success; everything else indicates a failure. Therefore, if the result is within that range, you
know that the server processed the message properly.

Free download pdf