[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

sockets between computers on the Net. As we’ve seen, though, the POP and SMTP
interfaces in Python hide all the details. Moreover, the scripts we’ve begun writing even
hide the Python interfaces and provide higher-level interactive tools.


Both the popmail and smtpmail scripts provide portable email tools but aren’t quite what
we’d expect in terms of usability these days. Later in this chapter, we’ll use what we’ve
seen thus far to implement a more interactive, console-based mail tool. In the next
chapter, we’ll also code a tkinter email GUI, and then we’ll go on to build a web-based
interface in a later chapter. All of these tools, though, vary primarily in terms of user
interface only; each ultimately employs the Python mail transfer modules we’ve met
here to transfer mail message text over the Internet with sockets.


Before we move on, one more SMTP note: just as for reading mail, we can use the
Python interactive prompt as our email sending client, too, if we type calls manually.
The following, for example, sends a message through my ISP’s SMTP server to two
recipient addresses assumed to be part of a mail list:


C:\...\PP4E\Internet\Email> python
>>> from smtplib import SMTP
>>> conn = SMTP('smtpout.secureserver.net')
>>> conn.sendmail(
... '[email protected]', # true sender
... ['[email protected]', '[email protected]'], # true recipients
... """From: [email protected]
... To: maillist
... Subject: test interactive smtplib
...
... testing 1 2 3...
... """)
{}
>>> conn.quit() # quit() required, Date added
(221, b'Closing connection. Good bye.')

We’ll verify receipt of this message in a later email client program; the “To” recipient
shows up as “maillist” in email clients—a completely valid use case for header manip-
ulation. In fact, you can achieve the same effect with the smtpmail-noTo script by sep-
arating recipient addresses at the “To?” prompt with a semicolon (e.g. [email protected];
[email protected]) and typing the email list’s name in the “To:” header line.
Mail clients that support mailing lists automate such steps.


Sending mail interactively this way is a bit tricky to get right, though—header lines are
governed by standards: the blank line after the subject line is required and significant,
for instance, and Date is omitted altogether (one is added for us). Furthermore, mail
formatting gets much more complex as we start writing messages with attachments. In
practice, the email package in the standard library is generally used to construct emails,
before shipping them off with smtplib. The package lets us build mails by assigning
headers and attaching and possibly encoding parts, and creates a correctly formatted
mail text. To learn how, let’s move on to the next section.


920 | Chapter 13: Client-Side Scripting

Free download pdf