Example 13-20. PP4E\Internet\Email\pymail.py
#!/usr/local/bin/python
"""
##########################################################################
pymail - a simple console email interface client in Python; uses Python
poplib module to view POP email messages, smtplib to send new mails, and
the email package to extract mail headers and payload and compose mails;
##########################################################################
"""
import poplib, smtplib, email.utils, mailconfig
from email.parser import Parser
from email.message import Message
fetchEncoding = mailconfig.fetchEncoding
def decodeToUnicode(messageBytes, fetchEncoding=fetchEncoding):
"""
4E, Py3.1: decode fetched bytes to str Unicode string for display or parsing;
use global setting (or by platform default, hdrs inspection, intelligent guess);
in Python 3.2/3.3, this step may not be required: if so, return message intact;
"""
return [line.decode(fetchEncoding) for line in messageBytes]
def splitaddrs(field):
"""
4E: split address list on commas, allowing for commas in name parts
"""
pairs = email.utils.getaddresses([field]) # [(name,addr)]
return [email.utils.formataddr(pair) for pair in pairs] # [name
def inputmessage():
import sys
From = input('From? ').strip()
To = input('To? ').strip() # datetime hdr may be set auto
To = splitaddrs(To) # possible many, name+
Subj = input('Subj? ').strip() # don't split blindly on ',' or ';'
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) # join for hdr, not send
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, To, str(msg)) # may also raise exc
948 | Chapter 13: Client-Side Scripting