Chapter 13 ■ SMtp
252
Getting Information from EHLO
Sometimes it is nice to know what kind of messages a remote SMTP server will accept. For instance, most SMTP
servers have a limit on what size message they permit, and if you fail to check first, then you may transmit a very large
message only to have it rejected when you have completed transmission.
In the original version of SMTP, a client would send an HELO command as the initial greeting to the server. A
set of extensions to SMTP, called ESMTP, has been developed to allow more powerful conversations. ESMTP-aware
clients will begin the conversation with EHLO, which signals an ESMTP-aware server that it can reply to with extended
information. This extended information includes the maximum message size, along with any optional SMTP features
that the server supports.
However, you must be careful to check the return code. Some servers do not support ESMTP. On those servers,
EHLO will just return an error. In that case, you must send an HELO command instead.
In the previous examples, I used sendmail() immediately after creating the SMTP object, so smtplib
automatically sent its own “hello” message to the server to get the conversation started for you. But if it sees you
attempt to send the EHLO or HELO command on your own, then the Python sendmail() method will not attempt to
send a hello command itself.
Listing 13-4 shows a program that gets the maximum size from the server and returns an error before sending if a
message would be too large.
Listing 13-4. Checking Message Size Restrictions
#!/usr/bin/env python3
Foundations of Python Network Programming, Third Edition
https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter13/ehlo.py
import smtplib, socket, sys
message_template = """To: {}
From: {}
Subject: Test Message from simple.py
Hello,
This is a test message sent to you from the ehlo.py program
in Foundations of Python Network Programming.
"""
def main():
if len(sys.argv) < 4:
name = sys.argv[0]
print("usage: {} server fromaddr toaddr [toaddr...]".format(name))
sys.exit(2)
server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:]
message = message_template.format(', '.join(toaddrs), fromaddr)