Foundations of Python Network Programming

(WallPaper) #1

Chapter 13 ■ SMtp


248


Because each server tends to add its Received header to the top of the e-mail message, this saves time and
prevents each server from having to search to the bottom of the Received headers that have been written so far. You
should read them backward: the oldest Received header will be the one listed last, so as you read up the screen toward
the top, you will be following the e-mail from its origin to its destination. Try it: bring up a recent e-mail message that
you have received, select its View All Message Headers or Show Original option, and look for the received headers
near the top. Did the message require more, or fewer, steps to reach your in box than you would have expected?


Introducing the SMTP Library


Python’s built-in SMTP implementation is in the Python Standard Library module smtplib, which makes it easy to do
simple tasks with SMTP.
In the examples that follow, the programs are designed to take several command-line arguments: the name of an
SMTP server, a sender address, and one or more recipient addresses. Please use them cautiously; name only an SMTP
server that you yourself run or that you know will be happy to receive your test messages, lest you wind up getting your
IP address banned for sending spam!
If you don’t know where to find an SMTP server, you might try running an e-mail daemon like postfix or exim
locally and then pointing these example programs at localhost. Some UNIX, Linux, and Mac OS X systems have an
SMTP server like one of these already listening for connections from the local machine.
Otherwise, consult your network administrator or Internet provider to obtain a proper hostname and port.
Note that you usually cannot just pick an e-mail server at random; many store or forward e-mail only from certain
authorized clients.
With that addressed, you are ready to move on to Listing 13-1, which illustrates a very simple SMTP program.


Listing 13-1. Sending E-mail with smtplib.sendmail()


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter13/simple.py


import sys, smtplib


message_template = """To: {}
From: {}
Subject: Test Message from simple.py


Hello,


This is a test message sent to you from the simple.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)

Free download pdf