August 2006
Intermediate to advanced
1600 pages
51h 46m
English
Let’s put together what we’ve learned about fetching, sending, parsing, and composing email in a simple but functional command-line console email tool. The script in Example 14-20 implements an interactive email session—users may type commands to read, send, and delete email messages.
Example 14-20. PP3E\Internet\Email\pymail.py
#!/usr/local/bin/python ########################################################################## # pymail - a simple console email interface client in Python; uses Python # POP3 mail interface module to view POP email account messages; uses # email package modules to extract mail message headers (not rfc822); ########################################################################## import poplib, smtplib, email.Utils from email.Parser import Parser from email.Message import Message def inputmessage( ): import sys From = raw_input('From? ').strip( ) To = raw_input('To? ').strip( ) # datetime hdr set auto To = To.split(';') Subj = raw_input('Subj? ').strip( ) print 'Type message text, end with line="."' text = '' while True: line = sys.stdin.readline( ) if line == '.\n': break text += line return From, To, Subj, text def sendmessage( ): From, To, Subj, text = inputmessage( ) msg = Message( ) msg['From'] = From msg['To'] = ';'.join(To) msg['Subject'] = Subj msg['Date'] = email.Utils.formatdate( ) # curr datetime, rfc2822 msg.set_payload(text) server = smtplib.SMTP(mailconfig.smtpservername) try: failed = server.sendmail(From, ...