program. The net effect is as if we had run mail interactively, but it happens inside
a running Python script.
Running the sendmail program
The open source sendmail program offers another way to initiate mail from a pro-
gram. Assuming it is installed and configured on your system, you can launch it
using Python tools like the os.popen call of the previous paragraph.
Using the standard smtplib Python module
Python’s standard library comes with support for the client-side interface to
SMTP—the Simple Mail Transfer Protocol—a higher-level Internet standard for
sending mail over sockets. Like the poplib module we met in the previous section,
smtplib hides all the socket and protocol details and can be used to send mail on
any machine with Python and a suitable socket-based Internet link.
Fetching and using third-party packages and tools
Other tools in the open source library provide higher-level mail handling packages
for Python; most build upon one of the prior three techniques.
Of these four options, smtplib is by far the most portable and direct. Using os.popen
to spawn a mail program usually works on Unix-like platforms only, not on Windows
(it assumes a command-line mail program), and requires spawning one or more pro-
cesses along the way. And although the sendmail program is powerful, it is also some-
what Unix-biased, complex, and may not be installed even on all Unix-like machines.
By contrast, the smtplib module works on any machine that has Python and an Internet
link that supports SMTP access, including Unix, Linux, Mac, and Windows. It sends
mail over sockets in-process, instead of starting other programs to do the work. More-
over, SMTP affords us much control over the formatting and routing of email.
SMTP Mail Sender Script
Since SMTP is arguably the best option for sending mail from a Python script, let’s
explore a simple mailing program that illustrates its interfaces. The Python script shown
in Example 13-19 is intended to be used from an interactive command line; it reads a
new mail message from the user and sends the new mail by SMTP using Python’s
smtplib module.
Example 13-19. PP4E\Internet\Email\smtpmail.py
#!/usr/local/bin/python
"""
###########################################################################
use the Python SMTP mail interface module to send email messages; this
is just a simple one-shot send script--see pymail, PyMailGUI, and
PyMailCGI for clients with more user interaction features; also see
popmail.py for a script that retrieves mail, and the mailtools pkg
for attachments and formatting with the standard library email package;
###########################################################################
"""
SMTP: Sending Email | 911