SMTP: Sending Email
There is a proverb in hackerdom that states that every useful computer program eventually grows complex enough to send email. Whether such wisdom rings true or not in practice, the ability to automatically initiate email from within a program is a powerful tool.
For instance, test systems can automatically email failure reports, user interface programs can ship purchase orders to suppliers by email, and so on. Moreover, a portable Python mail script could be used to send messages from any computer in the world with Python and an Internet connection. Freedom from dependence on mail programs like Outlook is an attractive feature if you happen to make your living traveling around teaching Python on all sorts of computers.
Luckily, sending email from within a Python script is just as easy as reading it. In fact, there are at least four ways to do so:
- Calling
os.popento launch a command-line mail program On some systems, you can send email from a script with a call of the form:
os.popen('mail -s "xxx" a@b.c', 'w').write(text)As we saw earlier in the book, the
popentool runs the command-line string passed to its first argument, and returns a file-like object connected to it. If we use an open mode ofw, we are connected to the command’s standard input stream—here, we write the text of the new mail message to the standard Unixmailcommand-line program. The net effect is as if we had runmailinteractively, but it happens inside a running Python script.- Running the