Foundations of Python Network Programming

(WallPaper) #1

Chapter 13 ■ SMtp


256


def send_message_securely(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("Remove server refused HELO; code:", code)
sys.exit(1)


if uses_esmtp and connection.has_extn('starttls'):
print("Negotiating TLS....")
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.set_default_verify_paths()
context.verify_mode = ssl.CERT_REQUIRED
connection.starttls(context=context)
code = connection.ehlo()[0]
if not (200 <= code <= 299):
print("Couldn't EHLO after STARTTLS")
sys.exit(5)
print("Using TLS connection.")
else:
print("Server does not support TLS; using normal connection.")


connection.sendmail(fromaddr, toaddrs, message)


if name == 'main':
main()


Notice that the call to sendmail() in the last few listings is the same, regardless of whether TLS is used. Once TLS
is started, the system hides that layer of complexity from you, so you do not need to worry about it.


Authenticated SMTP


Finally, there is the topic of authenticated SMTP, where your ISP, university, or company e-mail server needs you to
log in with a username and password, to prove that you are not a spammer, before they allow you to send e-mail.
For maximum security, TLS should be used in conjunction with authentication; otherwise your password
(and username, for that matter) will be visible to anyone observing the connection. The proper way to do this
is to establish the TLS connection first and then send your authentication information only over the encrypted
communications channel.
Authentication itself is simple; smtplib provides a login() function that takes a username and a password.
Listing 13-6 shows an example. To avoid repeating code already shown in previous listings, this listing does not take
the advice provided in the previous paragraph, and it sends the username and password over an unauthenticated
connection that will send them in the clear.

Free download pdf