id
int64
0
25.6k
text
stringlengths
0
4.59k
5,500
by the parser and attached to the message object this is especially important if we need to save the data to file--we either have to store as bytes in binary mode filesor specify the correct (or at least compatibleunicode encoding in order to use such strings for text-mode files decoding manually works the same wayq get_payload(decode= decode(unicodedecodeerror'utf codec can' decode bytes in position - unexpected get_content_charset('latin get_payload(decode= decode('latin ''aabq get_payload(decode= decode( get_content_charset()'aabknown type allow any type in factall the header details are available on message objectsif we know where to look the character set can also be absent entirelyin which case it' returned as noneclients need to define policies for such ambiguous text (they might try common typesguessor treat the data as raw byte string) ['content-type'mapping interface 'text/plaincharset="latin " items([('content-type''text/plaincharset="latin "')('mime-version'' ')('content-transfer-encoding''base ')> get_params(header='content-type'[('text/plain''')('charset''latin ') get_param('charset'header='content-type''latin param interface charset get_content_charset(if charsetprint( get_payload(decode= decode(charset)aab might be missing this handles encodings for message text parts in parsed emails for composing new emailswe still must apply session-wide user settings or allow the user to specify an encoding for each part interactively in some of this book' email clientspayload conversions are performed as needed--using encoding information in message headers after parsing and provided by users during mail composition message header encodingsemail package support on related notethe email package also provides support for encoding and decoding message headers themselves ( fromsubjectper email standards when they are not simple text such headers are often called internationalized (or nheadersbecause they support inclusion of non-ascii character set text in emails this term is also sometimes used to refer to encoded text of message payloadsunlike message headersemailparsing and composing mail content
5,501
binary data such as images (as we'll see in the next sectionlike mail payload partsi headers are encoded specially for emailand may also be encoded per unicode for instancehere' how to decode an encoded subject line from an arguably spammish email that just showed up in my inboxits =?utf- ?qpreamble declares that the data following it is utf- encoded unicode textwhich is also mimeencoded per quoted-printable for transmission in email (in shortunlike the prior section' part payloadswhich declare their encodings in separate header linesheaders themselves may declare their unicode and mime encodings by embedding them in their own content this way)rawheader '=?utf- ? ?introducing= top= values= = = special= selecti on= of= great= money= savers?=from email header import decode_header decode per email+mime decode_header(rawheader[( 'introducing top valuesa special selection of great money savers''utf- ')binenc decode_header(rawheader)[ and decode per unicode binenc ( 'introducing top valuesa special selection of great money savers''utf- 'bin decode(enc'introducing top valuesa special selection of great money saverssubtlythe email package can return multiple parts if there are encoded substrings in the headerand each must be decoded individually and joined to produce decoded header text even more subtlyin this package returns all bytes when any substring (or the entire headeris encoded but returns str for fully unencoded headerand uncoded substrings returned as bytes are encoded per "raw-unicode-escapein the package--an encoding scheme useful to convert str to bytes when no encoding type appliesfrom email header import decode_header 'man where did you get that assistant? '=?utf- ? ?man_where_did_you_get_that_assistant= ?= 'man where did you get that =?utf- ? ?assistant= ?=strdon' decode(decode_header( [('man where did you get that assistant?'none)bytesdo decode(decode_header( [( 'man where did you get that assistant?''utf- ')bytesdo decode(using raw-unicode-escape applied in package decode_header( [( 'man where did you get that'none)( 'assistant?''utf- ')join decoded parts if more than one client-side scripting
5,502
join(abytes decode('raw-unicode-escapeif enc =none else encfor (abytesencin parts'man where did you get that assistant?we'll use logic similar to the last step here in the mailtools package aheadbut also retain str substrings intact without attempting to decode late-breaking newsas write this in mid- it seems possible that this mixed typenonpolymorphicand franklynon-pythonic api behavior may be addressed in future python release in response to rant posted on the python developers list by book author whose work you might be familiar withthere is presently vigorous discussion of the topic there among other ideas is proposal for bytes-like type which carries with it an explicit unicode encodingthis may make it possible to treat some text cases in more generic fashion while it' impossible to foresee the outcome of such proposalsit' good to see that the issues are being actively explored stay tuned to this book' website for further developments in the python library api and unicode stories message address header encodings and parsingand header creation one wrinkle pertaining to the prior sectionfor message headers that contain email addresses ( from)the name component of the name/address pair might be encoded this way as well because the email package' header parser expects encoded substrings to be followed by whitespace or the end of stringwe cannot ask it to decode complete address-related header--quotes around name components will fail to support such internationalized address headerswe must also parse out the first part of the email address and then decode first of allwe need to extract the name and address parts of an email address using email package toolsfrom email utils import parseaddrformataddr parseaddr('"smithbob' ('smithbob''bob@bob com'formataddr( '"smithbobsplit into name/addr pair unencoded addr parseaddr('bob smith 'unquoted name part ('bob smith''bob@bob com'formataddr(parseaddr('bob smith ')'bob smith parseaddr('bob@bob com'('''bob@bob com'formataddr(parseaddr('bob@bob com')'bob@bob comsimpleno name fields with multiple addresses ( toseparate individual addresses by commas since email names might embed commastooblindly splitting on commas to run each emailparsing and composing mail content
5,503
address individuallygetaddresses ignores commas in names when spitting apart separate addressesand parseaddr doestoobecause it simply returns the first pair in the getaddresses result (some line breaks were added to the following for legibility)from email utils import getaddresses multi '"smithbobbob smith bob@bob com"bobgetaddresses([multi][('smithbob''bob@bob com')('bob smith''bob@bob com')('''bob@bob com')('bob''bob@bob com')[formataddr(pairfor pair in getaddresses([multi])['"smithbob''bob smith ''bob@bob com''bob ''join([formataddr(pairfor pair in getaddresses([multi])]'"smithbobbob smith bob@bob combob getaddresses(['bob@bob com']('''bob@bob com')handles single address cases too nowdecoding email addresses is really just an extra step before and after the normal header decoding logic we saw earlierrawfromheader '"=?utf- ? ?walmart?=from email utils import parseaddrformataddr from email header import decode_header nameaddr parseaddr(rawfromheadernameaddr ('=?utf- ? ?walmart?=''newsletters@walmart com'split into name/addr parts abytesaenc decode_header(name)[ abytesaenc ( 'walmart''utf- 'do email+mime decoding name abytes decode(aencname 'walmartdo unicode decoding formataddr((nameaddr)'walmart put parts back together although from headers will typically have just one addressto be fully robust we need to apply this to every address in headerssuch as toccand bcc againthe multiaddress getaddresses utility avoids comma clashes between names and address separatorssince it also handles the single address caseit suffices for from headers as wellrawfromheader '"=?utf- ? ?walmart?=rawtoheader rawfromheader 'rawfromheader rawtoheader client-side scripting
5,504
ters@walmart com>pairs getaddresses([rawtoheader]pairs [('=?utf- ? ?walmart?=''newsletters@walmart com')('=?utf- ? ?walmart?=''ne wsletters@walmart com')addrs [for nameaddr in pairsabytesaenc decode_header(name)[ email+mime name abytes decode(aencunicode addrs append(formataddr((nameaddr))one or more addrs 'join(addrs'walmart walmart these tools are generally forgiving for unencoded content and return them intact to be robustthoughthe last portion of code here should also allow for multiple parts returned by decode_header (for encoded substrings)none encoding values for parts (for unencoded substrings)and str substring values instead of bytes (for fully unencoded namesdecoding this way applies both mime and unicode decoding steps to fetched mails creating properly encoded headers for inclusion in new mails composed and sent is similarly straightforwardfrom email header import make_header hdr make_header([( ' \xc \xe ''latin- ')]print(hdraabac print(hdr encode()=?iso- - ? ? = = ?decode_header(hdr encode()[( ' \xc \xe ''iso- - ')this can be applied to entire headers such as subjectas well as the name component of each email address in an address-related header line such as from and to (use getaddresses to split into individual addresses first if neededthe header object provides an alternative interfaceboth techniques handle additional detailssuch as line lengthsfor which we'll defer to python manualsfrom email header import header header( ' \xe \xc 'charset='latin- ' encode('=?iso- - ? ? = = ?= header('spam'charset='ascii'same as header('spam' encode('spamthe mailtools package ahead and its pymailgui client of will use these interfaces to automatically decode message headers in fetched mails per their content for displayand to encode headers sent that are not in ascii format that latter also emailparsing and composing mail content
5,505
allow these to pass this may encroach on some smtp server issues which we don' have space to address in this book see the web for more on smtp headers handling for more on headers decodingsee also file _test- -headers py in the examples packageit decodes additional subject and address-related headers using mailtools methodsand displays them in tkinter text widget-- foretaste of how these will be displayed in pymailgui workaroundmessage text generation for binary attachment payloads is broken our last two email unicode issues are outright bugs which we must work around todaythough they will almost certainly be fixed in future python release the first breaks message text generation for all but trivial messages--the email package today no longer supports generation of full mail text for messages that contain any binary partssuch as images or audio files without coding workaroundsonly simple emails that consist entirely of text parts can be composed and generated in python ' email packageany mime-encoded binary part causes mail text generation to fail this is bit tricky to understand without poring over email' source code (whichthankfullywe can in the land of open source)but to demonstrate the issuefirst notice how simple text payloads are rendered as full message text when printed as we've already seenc:\pp \internet\emailpython from email message import message message( ['from''bob@bob comm set_payload(open('text txt'read()print(mfrombob@bob com generic message object payload is str text print uses as_string(spam spam spamas we've also seenfor conveniencethe email package also provides subclasses of the message objecttailored to add message headers that provide the extra descriptive details used by email clients to know how to process the datafrom email mime text import mimetext text open('text txt'read( mimetext(textm['from''bob@bob comprint(mcontent-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit frombob@bob com client-side scripting message subclass with headers payload is str text
5,506
spam spamthis works for textbut watch what happens when we try to render message part with truly binary datasuch as an image that could not be decoded as unicode textfrom email message import message generic message object message( ['from''bob@bob combytes open('monkeys jpg''rb'read(read binary bytes (not unicodem set_payload(byteswe set the payload to bytes print(mtraceback (most recent call last)lines omitted file " :\python \lib\email\generator py"line in _handle_text raise typeerror('string payload expected%stype(payload)typeerrorstring payload expectedm get_payload()[: '\xff\xd \xff\xe \ \ jfif\ \ \ \ \ \ \ \ the problem here is that the email package' text generator assumes that the message' payload data is base (or similarencoded str text string by generation timenot bytes reallythe error is probably our fault in this casebecause we set the payload to raw bytes manually we should use the mimeimage mime subclass tailored for imagesif we dothe email package internally performs base mime email encoding on the data when the message object is created unfortunatelyit still leaves it as bytesnot strdespite the fact the whole point of base is to change binary data to text (though the exact unicode flavor this text should take may be unclearthis leads to additional failures in python from email mime image import mimeimage message sublcass with hdrs+base bytes open('monkeys jpg''rb'read(read binary bytes again mimeimage(bytesmime class does base on data print(mtraceback (most recent call last)lines omitted file " :\python \lib\email\generator py"line in _handle_text raise typeerror('string payload expected%stype(payload)typeerrorstring payload expectedm get_payload()[: '/ / aaqskzjrgabaqeaeab aad/ wbdaaibaqibthis is already base text get_payload()[: decode('ascii''/ / aaqskzjrgabaqeaeab aad/ wbdaaibaqibbut it' still bytes internallyin other wordsnot only does the python email package not fully support the python unicode/bytes dichotomyit was actually broken by it luckilythere' workaround for this case to address this specific issuei opted to create custom encoding function for binary mime attachmentsand pass it in to the email package' mime message object emailparsing and composing mail content
5,507
mailtools package of this (example - because it is used by email to encode from bytes to text at initialization timeit is able to decode to ascii text per unicode as an extra stepafter running the original call to perform base encoding and arrange content-encoding headers the fact that email does not do this extra unicode decoding step itself is genuine bug in that package (albeitone introduced by changes elsewhere in python standard libraries)but the workaround does its jobin mailtools mailsender module ahead in this def fix_encode_base (msgobj)from email encoders import encode_base encode_base (msgobjwhat email does normallyleaves bytes bytes msgobj get_payload(bytes fails in email pkg on text gen text bytes decode('ascii'decode to unicode str so text gen works line splitting logic omitted msgobj set_payload('\njoin(lines)from email mime image import mimeimage from mailtools mailsender import fix_encode_base bytes open('monkeys jpg''rb'read( mimeimage(bytes_encoder=fix_encode_base print( as_string()[: ]content-typeimage/jpeg mime-version content-transfer-encodingbase use custom workaround convert to ascii str / / aaqskzjrgabaqeaeab aad/ wbdaaibaqibaqicagicagicawudawmdawyebamfbwyhbwcg bwcicqsjcagkcachcg kcgsmdawmbwkodw mdgsmdaz/ wbdaqicagmdawydawymcacidawmdawm dawmdawmdawmdawmdawmdawmdawmdawmdawmdawmdawmdawmdawmdawmdaz/waarcahoavqdasia ahebaxeb/ qahwaaaqubaqebaqeaaaaaaaaaaaecawqfbgcicqol/ qatraaagedawieawufbaqa aaf aqidaaqrbrihmuege fhbyjxfdkbkaeii kxwrvs fakm jyggkkfhcygroljicokso nty odk rfrkdisuptvfvwv hzwmnkzwznaglqc print(mto print the entire messagevery long another possible workaround involves defining custom mimeimage class that is like the original but does not attempt to perform base ending on creationthat waywe could encode and translate to str before message object creationbut still make use of the original class' header-generation logic if you take this routethoughyou'll find that it requires repeating (reallycutting and pastingfar too much of the original logic to be reasonable--this repeated code would have to mirror any future email changesfrom email mime nonmultipart import mimenonmultipart class myimage(mimenonmultipart)def __init__(selfimagedatasubtype)mimenonmultipart __init__(self'image'subtypeself set_payload(_imagedatarepeat all the base logic herewith an extra ascii unicode decode myimage(text_from_bytesinterestinglythis regression in email actually reflects an unrelated change in python' base module made in which was completely benign until the python bytes client-side scripting
5,508
because bytes was really str in xthoughbecause base returns bytesthe normal mail encoder in email also leaves the payload as byteseven though it' been encoded to base text form this in turn breaks email text generationbecause it assumes the payload is text in this caseand requires it to be str as is common in large-scale software systemsthe effects of some changes may have been difficult to anticipate or accommodate in full by contrastparsing binary attachments (as opposed to generating text for themworks fine in xbecause the parsed message payload is saved in message objects as base encoded str stringnot bytesand is converted to bytes only when fetched this bug seems likely to also go away in future python and email package (perhaps even as simple patch in python )but it' more serious than the other unicode decoding issues described herebecause it prevents mail composition for all but trivial mails the flexibility afforded by the package and the python language allows such workaround to be developed external to the packagerather than hacking the package' code directly with open source and forgiving apisyou rarely are truly stuck late-breaking newsthis section' bug is scheduled to be fixed in python making our workaround here unnecessary in this and later python releases this is per communications with members of python' email special interest group (on the "email-sigmailing listregrettablythis fix didn' appear until after this and its examples had been written ' like to remove the workaround and its description entirelybut this book is based on python both before and after the fix was incorporated so that it works under python alphatoothoughthe workaround code ahead was specialized just before publication to check for bytes prior to decoding moreoverthe workaround still must manually split lines in base databecause still does not workaroundmessage composition for non-ascii text parts is broken our final email unicode issue is as severe as the prior onechanges like that of the prior section introduced yet another regression for mail composition in shortit' impossible to make text message parts today without specializing for different unicode encodings some types of text are automatically mime-encoded for transmission unfortunatelybecause of the str/bytes splitthe mime text message class in email now requires different string object types for different unicode encodings the net effect is that you now have to know how the email package will process your text data when making text message objector repeat most of its logic redundantly for exampleto properly generate unicode encoding headers and apply required mime encodingshere' how we must proceed today for common unicode text typesemailparsing and composing mail content
5,509
print(mmime-version content-typetext/plaincharset="us-asciicontent-transfer-encoding bit abc mimetext('abc'_charset='latin- 'print(mmime-version content-typetext/plaincharset="iso- - content-transfer-encodingquoted-printable abc mimetext( 'abc'_charset='utf- 'print(mcontent-typetext/plaincharset="utf- mime-version content-transfer-encodingbase pass text for ascii pass text for latin- but not for 'latin 'ahead pass bytes for utf ywjj this worksbut if you look closelyyou'll notice that we must pass str to the first twobut bytes to the third that requires that we special-case code for unicode types based upon the package' internal operation types other than those expected for unicode encoding don' work at allbecause of newly invalid str/bytes combinations that occur inside the email package in mimetext('abc'_charset='ascii' mimetext( 'abc'_charset='ascii'bugassumes str traceback (most recent call last)lines omitted file " :\python \lib\email\encoders py"line in encode_ or bit orig encode('ascii'attributeerror'bytesobject has no attribute 'encodem mimetext('abc'_charset='latin- ' mimetext( 'abc'_charset='latin- 'bugqp uses str traceback (most recent call last)lines omitted file " :\python \lib\email\quoprimime py"line in body_encode if line endswith(crlf)typeerrorexpected an object with the buffer interface mimetext( 'abc'_charset='utf- ' mimetext('abc'_charset='utf- 'bugbase uses bytes traceback (most recent call last)lines omitted file " :\python \lib\email\base mime py"line in body_encode enc a_base ( [ : max_unencoded]decode("ascii"typeerrormust be bytes or buffernot str moreoverthe email package is pickier about encoding name synonyms than python and most other tools are"latin- is detected as quoted-printable mime typebut client-side scripting
5,510
used for the "latin unicode type earlier in this section--an encoding choice that is irrelevant to any recipient that understands the "latin synonymincluding python itself unfortunatelythat means that we also need to pass in different string type if we use synonym the package doesn' understand todaym mimetext('abc'_charset='latin- 'print(mmime-version content-typetext/plaincharset="iso- - content-transfer-encodingquoted-printable str for 'latin- abc mimetext('abc'_charset='latin 'traceback (most recent call last)lines omitted file " :\python \lib\email\base mime py"line in body_encode enc a_base ( [ : max_unencoded]decode("ascii"typeerrormust be bytes or buffernot str mimetext( 'abc'_charset='latin 'print(mcontent-typetext/plaincharset="latin mime-version content-transfer-encodingbase bytes for 'latin 'ywjj there are ways to add aliases and new encoding types in the email packagebut they're not supported out of the box programs that care about being robust would have to cross-check the user' spellingwhich may be valid for python itselfagainst that expected by email this also holds true if your data is not ascii in general--you'll have to first decode to text in order to use the expected "latin- name because its quotedprintable mime encoding expects streven though bytes are required if "latin triggers the default base mimem mimetext( ' \xe '_charset='latin 'print(mcontent-typetext/plaincharset="latin mime-version content-transfer-encodingbase qerc mimetext( ' \xe '_charset='latin- 'traceback (most recent call last)lines omitted file " :\python \lib\email\quoprimime py"line in body_encode if line endswith(crlf)typeerrorexpected an object with the buffer interface mimetext( ' \xe bdecode('latin ')_charset='latin- 'print(memailparsing and composing mail content
5,511
content-typetext/plaincharset="iso- - content-transfer-encodingquoted-printable = in factthe text message object doesn' check to see that the data you're mimeencoding is valid per unicode in general--we can send invalid utf text but the receiver may have trouble decoding itm mimetext( ' \xe '_charset='utf- 'print(mcontent-typetext/plaincharset="utf- mime-version content-transfer-encodingbase qerc ' \xe bdecode('utf 'unicodedecodeerror'utf codec can' decode bytes in position - unexpected import base base decode( 'qerc' ' \xe bbase decode( 'qerc'decode('utf'unicodedecodeerror'utf codec can' decode bytes in position - unexpected so what to do if we need to attach message text to composed messages if the text' datatype requirement is indirectly dictated by its unicode encoding namethe generic message superclass doesn' help here directly if we specify an encodingas it exhibits the same encoding-specific behaviorm message( set_payload('spam'charset='us-ascii'print(mmime-version content-typetext/plaincharset="us-asciicontent-transfer-encoding bit spam message( set_payload( 'spam'charset='us-ascii'attributeerror'bytesobject has no attribute 'encodem set_payload('spam'charset='utf- 'typeerrormust be bytes or buffernot str although we could try to work around these issues by repeating much of the code that email runsthe redundancy would make us hopelessly tied to its current implementation and dependent upon its future changes the followingfor exampleparrots the steps that email runs internally to create text message object for ascii encoding textunlike the mimetext classthis approach allows all data to be read from files as binary byte stringseven if it' simple ascii client-side scripting
5,512
add_header('content-type''text/plain' ['mime-version'' set_param('charset''us-ascii' add_header('content-transfer-encoding'' bit'data 'spamm set_payload(data decode('ascii')data read as bytes here print(mmime-version content-typetext/plaincharset="us-asciicontent-transfer-encoding bit spam print(mimetext('spam'_charset='ascii')mime-version content-typetext/plaincharset="us-asciicontent-transfer-encoding bit samebut type-specific spam to do the same for other kinds of text that require mime encodingjust insert an extra encoding stepalthough we're concerned with text parts herea similar imitative approach could address the binary parts text generation bug we met earlierm message( add_header('content-type''text/plain' ['mime-version'' set_param('charset''utf- ' add_header('content-transfer-encoding''base 'data 'spamfrom binascii import a_base add mime encode if needed data a_base (datadata read as bytes here too set_payload(data decode('ascii')print(mmime-version content-typetext/plaincharset="utf- content-transfer-encodingbase bhbq=print(mimetext( 'spam'_charset='utf- ')content-typetext/plaincharset="utf- mime-version content-transfer-encodingbase samebut type-specific bhbq=this worksbut besides the redundancy and dependency it createsto use this approach broadly we' also have to generalize to account for all the various kinds of unicode encodings and mime encodings possiblelike the email package already does internally we might also have to support encoding name synonyms to be flexibleadding further redundancy in other wordsthis requires additional workand in the endwe' still have to specialize our code for different unicode types emailparsing and composing mail content
5,513
today it seems the best we can do hereapart from hoping for an improved email package in few yearstimeis to specialize text message construction calls by unicode typeand assume both that encoding names match those expected by the package and that message data is valid for the unicode type selected here is the sort of arguably magic code that the upcoming mailtools package (again in example - will apply to choose text typesfrom email charset import charsetbase qp for in ('us-ascii''latin- ''utf ''latin ''ascii')cset charset(ebenc cset body_encoding if benc in (noneqp)print(ebenc'text'read/fetch data as str elseprint(ebenc'binary'read/fetch data as bytes us-ascii none text latin- text utf binary latin binary ascii none text we'll proceed this way in this bookwith the major caveat that this is almost certainly likely to require changes in the future because of its strong coupling with the current email implementation late-breaking newslike the prior sectionit now appears that this section' bug will also be fixed in python making the workaround here unnecessary in this and later python releases the nature of the fix is unknownthoughand we still need the fix for the version of python current when this was written as of just before publicationthe alpha release of is still somewhat type specific on this issuebut now accepts either str or bytes for text that triggers base encodingsinstead of just bytes summarysolutions and workarounds the email package in python provides powerful tools for parsing and composing mailsand can be used as the basis for full-featured mail clients like those in this book with just few workarounds as you can seethoughit is less than fully functional today because of thatfurther specializing code to its current api is perhaps temporary solution short of writing our own email parser and composer (not practical option in finitely-sized book!)some compromises are in order here moreoverthe inherent complexity of unicode support in email places some limits on how much we can pursue this thread in this book client-side scripting
5,514
composedand respect the unicode encodings in text parts and mail headers of messages fetched to make this work with the partially crippled email package in python thoughwe'll apply the following unicode policies in various email clients in this bookuse user preferences and defaults for the preparse decoding of full mail text fetched and encoding of text payloads sent use header informationif availableto decode the bytes payloads returned by get_payload when text parts must be treated as str textbut use binary mode files to finesse the issue in other contexts use formats prescribed by email standard to decode and encode message headers such as from and subject if they are not simple text apply the fix described to work around the message text generation issue for binary parts special-case construction of text message objects according to unicode types and email behavior these are not necessarily complete solutions for examplesome of this edition' email clients allow for unicode encodings for both text attachments and mail headersbut they do nothing about encoding the full text of messages sent beyond the policies inherited from smtplib and implement policies that might be inconvenient in some use cases but as we'll seedespite their limitationsour email clients will still be able to handle complex email tasks and very large set of emails againsince this story is in flux in python todaywatch this book' website for updates that may improve or be required of code that uses email in the future future email may handle unicode encodings more accurately like python xthoughbackward compatibility may be sacrificed in the process and require updates to this book' code for more on this issuesee the web as well as up-to-date python release notes although this quick tour captures the basic flavor of the interfacewe need to step up to larger examples to see more of the email package' power the next section takes us on the first of those steps console-based email client let' put together what we've learned about fetchingsendingparsingand composing email in simple but functional command-line console email tool the script in example - implements an interactive email session--users may type commands to readsendand delete email messages it uses poplib and smtplib to fetch and sendand uses the email package directly to parse and compose console-based email client
5,515
#!/usr/local/bin/python ""#########################################################################pymail simple console email interface client in pythonuses python poplib module to view pop email messagessmtplib to send new mailsand the email package to extract mail headers and payload and compose mails#########################################################################""import poplibsmtplibemail utilsmailconfig from email parser import parser from email message import message fetchencoding mailconfig fetchencoding def decodetounicode(messagebytesfetchencoding=fetchencoding)"" epy decode fetched bytes to str unicode string for display or parsinguse global setting (or by platform defaulthdrs inspectionintelligent guess)in python this step may not be requiredif soreturn message intact""return [line decode(fetchencodingfor line in messagebytesdef splitaddrs(field)"" esplit address list on commasallowing for commas in name parts ""pairs email utils getaddresses([field][(name,addr)return [email utils formataddr(pairfor pair in pairs[name def inputmessage()import sys from input('from'strip(to input('to'strip(datetime hdr may be set auto to splitaddrs(topossible manynameokay subj input('subj'strip(don' split blindly on ',or ';print('type message textend with line="'text 'while trueline sys stdin readline(if line =\ 'break text +line return fromtosubjtext def sendmessage()fromtosubjtext inputmessage(msg message(msg['from'from msg['to''join(tomsg['subject'subj msg['date'email utils formatdate(msg set_payload(textserver smtplib smtp(mailconfig smtpservernametryfailed server sendmail(fromtostr(msg) client-side scripting join for hdrnot send curr datetimerfc may also raise exc
5,516
print('error send failed'elseif failedprint('failed:'faileddef connect(servernameuserpasswd)print('connecting 'server poplib pop (servernameserver user(userserver pass_(passwdprint(server getwelcome()return server connectlog in to mail server pass is reserved word print returned greeting message def loadmessages(servernameuserpasswdloadfrom= )server connect(servernameuserpasswdtryprint(server list()(msgcountmsgbytesserver stat(print('there are'msgcount'mail messages in'msgbytes'bytes'print('retrieving 'msglist [fetch mail now for in range(loadfrommsgcount+ )empty if low >high (hdrmessageoctetsserver retr(isave text on list message decodetounicode(message epy bytes to str msglist append('\njoin(message)leave mail on server finallyserver quit(unlock the mail box assert len(msglist=(msgcount loadfrom msg nums start at return msglist def deletemessages(servernameuserpasswdtodeleteverify=true)print('to be deleted:'todeleteif verify and input('delete?')[: not in [' '' ']print('delete cancelled 'elseserver connect(servernameuserpasswdtryprint('deleting messages from server 'for msgnum in todeletereconnect to delete mail server dele(msgnummbox locked until quit(finallyserver quit(def showindex(msglist)count show some mail headers for msgtext in msglistmsghdrs parser(parsestr(msgtextheadersonly=trueexpects str in count + print('% :\ % bytes(countlen(msgtext))for hdr in ('from''to''date''subject')tryprint('\ %- =>% (hdrmsghdrs[hdr])except keyerrorprint('\ %- =>(unknown)hdrif count = console-based email client
5,517
pause after each def showmessage(imsglist)if < <len(msglist)#print(msglist[ - ]oldprints entire mail--hdrs+text print('- msg parser(parsestr(msglist[ - ]expects str in content msg get_payload(prints payloadstringor [messagesif isinstance(contentstr)keep just one end-line at end content content rstrip('\nprint(contentprint('- to get text onlysee email parsers elseprint('bad message number'def savemessage(imailfilemsglist)if < <len(msglist)savefile open(mailfile' 'encoding=mailconfig fetchencoding savefile write('\nmsglist[ - '-'* '\ 'elseprint('bad message number'def msgnum(command)tryreturn int(command split()[ ]exceptreturn - assume this is bad helptext ""available commandsi index display nlist all messages (or just message nd nmark all messages for deletion (or just message ns nsave all messages to file (or just message nm compose and send new mail message quit pymail display this help text ""def interact(msglistmailfile)showindex(msglisttodelete [while truetrycommand input('[pymailaction(ildsmq?'except eoferrorcommand 'qif not commandcommand '*quit if command =' 'break index elif command[ =' ' client-side scripting
5,518
list elif command[ =' 'if len(command= for in range( len(msglist)+ )showmessage(imsglistelseshowmessage(msgnum(command)msglistsave elif command[ =' 'if len(command= for in range( len(msglist)+ )savemessage(imailfilemsglistelsesavemessage(msgnum(command)mailfilemsglistdelete elif command[ =' 'if len(command= delete all later todelete list(range( len(msglist)+ ) requires list elsedelnum msgnum(commandif ( <delnum <len(msglist)and (delnum not in todelete)todelete append(delnumelseprint('bad message number'mail elif command[ =' 'sendmessage(#execfile('smtpmail py'{}send new mail via smtp altrun file in own namespace elif command[ ='?'print(helptextelseprint('what-type "?for commands help'return todelete if __name__ ='__main__'import getpassmailconfig mailserver mailconfig popservername ex'pop rmi netmailuser mailconfig popusername ex'lutzmailfile mailconfig savemailfile exr' :\stuff\savemailmailpswd getpass getpass('password for % ?mailserverprint('[pymail email client]'msglist loadmessages(mailservermailusermailpswdload all todelete interact(msglistmailfileif todeletedeletemessages(mailservermailusermailpswdtodeleteprint('bye ' console-based email client
5,519
already metplus handful of new techniquesloads this client loads all email from the server into an in-memory python list only onceon startupyou must exit and restart to reload newly arrived email saves on demandpymail saves the raw text of selected message into local filewhose name you place in the mailconfig module of example - deletions we finally support on-request deletion of mail from the server herein pymailmails are selected for deletion by numberbut are still only physically removed from your server on exitand then only if you verify the operation by deleting only on exitwe avoid changing mail message numbers during session--under popdeleting mail not at the end of the list decrements the number assigned to all mails following the one deleted since mail is cached in memory by pymailfuture operations on the numbered messages in memory can be applied to the wrong mail if deletions were done immediately parsing and composing messages pymail now displays just the payload of message on listing commandsnot the entire raw textand the mail index listing only displays selected headers parsed out of each message python' email package is used to extract headers and content from messageas shown in the prior section similarlywe use email to compose message and ask for its string to ship as mail by nowi expect that you know enough to read this script for deeper lookso instead of saying more about its design herelet' jump into an interactive pymail session to see how it works running the pymail console client let' start up pymail to read and delete email at our mail server and send new messages pymail runs on any machine with python and socketsfetches mail from any email server with pop interface on which you have an accountand sends mail via the smtp server you've named in the mailconfig module we wrote earlier (example - here it is in action running on my windows laptop machineits operation is identical on other machines thanks to the portability of both python and its standard library #there will be more on pop message numbers when we study mailtools later in this interestinglythe list of message numbers to be deleted need not be sortedthey remain valid for the duration of the delete connectionso deletions earlier in the list don' change numbers of messages later in the list while you are still connected to the pop server we'll also see that some subtle issues may arise if mails in the server inbox are deleted without pymail' knowledge ( by your isp or another email client)although very raresuffice it to say for now that deletions in this script are not guaranteed to be accurate client-side scripting
5,520
require no password)and wait for the pymail email list index to appearas isthis version loads the full text of all mails in the inbox on startupc:\pp \internet\emailpymail py password for pop secureserver net[pymail email clientconnecting '+ok ( '+ok '[ ' ' ' ' ' ' ' ' ' ' ' '] there are mail messages in bytes retrieving bytes from =>lutz@rmi net to =>pp @learning-python com date =>wed may : : - (edtsubject => ' lumberjackand ' okay bytes from =>lutz@learning-python com to =>pp @learning-python com date =>wed may : : - subject =>testing bytes from =>eric the half bee@yahoo com to =>pp @learning-python com date =>thu may : : - subject => bytes from =>pp @learning-python com to =>pp @learning-python com date =>thu may : : - subject =>testing smtpmail bytes from =>eric the half bee@aol com to =>nobody in particular@marketing com date =>thu may : : - subject => [press enter key bytes from =>pp @learning-python com to =>maillist date =>thu may : : - subject =>test interactive smtplib [pymailaction(ildsmq? testing [pymailaction(ildsmq? fiddle de dumfiddle de deeeric the half bee [pymailaction(ildsmq? console-based email client
5,521
type command letters to process it the command lists (printsthe contents of given mail numberherewe just used it to list two emails we sent in the preceding sectionwith the smtpmail scriptand interactively pymail also lets us get command helpdelete messages (deletions actually occur at the server on exit from the program)and save messages away in local text file whose name is listed in the mailconfig module we saw earlier[pymailaction(ildsmq?available commandsi index display nlist all messages (or just message nd nmark all messages for deletion (or just message ns nsave all messages to file (or just message nm compose and send new mail message quit pymail display this help text [pymailaction(ildsmq? [pymailaction(ildsmq? nowlet' pick the mail compose option--pymail inputs the mail partsbuilds mail text with emailand ships it off with smtplib you can separate recipients with commaand use either simple "addror full "name address pairs if desired because the mail is sent by smtpyou can use arbitrary from addresses herebut againyou generally shouldn' do that (unlessof courseyou're trying to come up with interesting examples for book)[pymailaction(ildsmq? fromcardinal@hotmail com topp @learning-python com subjamong our weapons are these type message textend with line=nobody expects the spanish inquisition[pymailaction(ildsmq? to be deleted[ delete? connecting '+ok deleting messages from server bye as mentioneddeletions really happen only on exit when we quit pymail with the commandit tells us which messages are queued for deletionand verifies the request once verifiedpymail finally contacts the mail server again and issues pop calls to delete the selected mail messages because deletions change message numbers in the server' inboxpostponing deletion until exit simplifies the handling of already loaded email (we'll improve on this in the pymailgui client of the next client-side scripting
5,522
startupthoughwe need to start pymail again to refetch mail from the server if we want to see the result of the mail we sent and the deletion we made hereour new mail shows up at the end as new number and the original mail assigned number in the prior session is gonec:\pp \internet\emailpymail py password for pop secureserver net[pymail email clientconnecting '+ok ( '+ok '[ ' ' ' ' ' ' ' ' ' ' ' '] there are mail messages in bytes retrieving bytes from =>lutz@rmi net to =>pp @learning-python com date =>wed may : : - (edtsubject => ' lumberjackand ' okay bytes from =>lutz@learning-python com to =>pp @learning-python com date =>wed may : : - subject =>testing bytes from =>eric the half bee@yahoo com to =>pp @learning-python com date =>thu may : : - subject => bytes from =>eric the half bee@aol com to =>nobody in particular@marketing com date =>thu may : : - subject => bytes from =>pp @learning-python com to =>maillist date =>thu may : : - subject =>test interactive smtplib [press enter key bytes from =>cardinal@hotmail com to =>pp @learning-python com date =>fri may : : - subject =>among our weapons are these [pymailaction(ildsmq? nobody expects the spanish inquisition[pymailaction(ildsmq? bye console-based email client
5,523
full name and address pairs in your email addresses this works just because the script employs email utilities described earlier to split up addresses and fully parse to allow commas as both separators and name characters the followingfor examplewould send to two and three recipientsrespectivelyusing mostly full address formats[pymailaction(ildsmq? from"moi to"pp "lu,tz[pymailaction(ildsmq? fromthe book to"pp "lu,tzlutz@rmi net finallyif you are running this liveyou will also find the mail save file on your machinecontaining the one message we asked to be saved in the prior sessionit' simply the raw text of saved emailswith separator lines this is both human and machinereadable--in principleanother script could load saved mail from this file into python list by calling the string object' split method on the file' text with the separator line as delimiter as shown in this bookit shows up in file :\temp\savemail txtbut you can configure this as you like in the mailconfig module the mailtools utility package the email package used by the pymail example of the prior section is collection of powerful tools--in factperhaps too powerful to remember completely at the minimumsome reusable boilerplate code for common use cases can help insulate you from some of its detailsby isolating module usagesuch code can also ease the migration to possible future email changes to simplify email interfacing for more complex mail clientsand to further demonstrate the use of standard library email toolsi developed the custom utility modules listed in this section-- package called mailtools mailtools is python modules packagea directory of codewith one module per tool classand an initialization module run when the directory is first imported this package' modules are essentially just wrapper layer above the standard library' email packageas well as its poplib and smtplib modules they make some assumptions about the way email is to be usedbut they are reasonable and allow us to forget some of the underlying complexity of the standard library tools employed in nutshellthe mailtools package provides three classes--to fetchsendand parse email messages these classes can be used as superclasses in order to mix in their methods to an application-specific classor as standalone or embedded objects that export their methods for direct calls we'll see these classes deployed both ways in this text as simple example of this package' tools in actionits selftest py module serves as self-test script when runit sends message from youto youwhich includes the selftest py file as an attachment it also fetches and displays some mail headers and client-side scripting
5,524
will lead us to full-blown email clients and websites in later two design notes worth mentioning up frontfirstnone of the code in this package knows anything about the user interface it will be used in (consoleguiwebor otheror does anything about things like threadsit is just toolkit as we'll seeits clients are responsible for deciding how it will be deployed by focusing on just email processing herewe simplify the codeas well as the programs that will use it secondeach of the main modules in this package illustrate unicode issues that confront python codeespecially when using the python email packagethe sender must address encodings for the main message textattachment input filessaved-mail output filesand message headers the fetcher must resolve full mail text encodings when new mails are fetched the parser must deal with encodings in text part payloads of parsed messagesas well as those in message headers in additionthe sender must provide workarounds for the binary parts generation and text part creation issues in email described earlier in this since these highlight unicode factors in generaland might not be solved as broadly as they might be due to limitations of the current python email packagei'll elaborate on each of these choices along the way the next few sections list mailtools source code togetherits files consist of roughly , lines of codeincluding whitespace and comments we won' cover all of this package' code in depth--study its listings for more detailsand see its self-test module for usage example alsofor more context and exampleswatch for the three clients that will use this package--the modified pymail py following this listingthe pymailgui client in and the pymailcgi server in by sharing and reusing this moduleall three systems inherit all its utilityas well as any future enhancements initialization file the module in example - implements the initialization logic of the mailtools packageas usualits code is run automatically the first time script imports through the package' directory notice how this file collects the contents of all the nested modules into the directory' namespace with from statements--because mailtools began life as single py filethis provides backward compatibility for existing clients we also must use package-relative import syntax here (from module)because python no longer includes the package' own directory on the module import search path (only the package' container is on the pathsince this is the root moduleglobal comments appear here as well the mailtools utility package
5,525
""#################################################################################mailtools packageinterface to mail server transfersused by pymail pymailguiand pymailcgidoes loadssendsparsingcomposingand deletingwith part attachmentsencodings (of both the email and unicdode kind)etc the parserfetcherand sender classes here are designed to be mixed-in to subclasses which use their methodsor used as embedded or standalone objectsthis package also includes convenience subclasses for silent modeand moreloads all mail text if pop server doesn' do topdoesn' handle threads or ui hereand allows askpassword to differ per subclassprogress callback funcs get statusall calls raise exceptions on error--client must handle in gui/otherthis changed from file to packagenested modules imported here for bw compat eneed to use package-relative import syntax throughoutbecause in py package dir in no longer on module import search path if package is imported elsewhere (from another directory which uses this package)also performs unicode decoding on mail text when fetched (see mailfetcher)as well as for some text part payloads which might have been email-encoded (see mailparser)tbdin savepartsshould file be opened in text mode for textcontypestbdin walknamedpartsshould we skip oddballs like message/delivery-statustbdunicode support has not been tested exhaustivelysee for more on the py email package and its limitationsand the policies used here#################################################################################""collect contents of all modules herewhen package dir imported directly from mailfetcher import from mailsender import epackage-relative from mailparser import export nested modules herewhen from mailtools import __all__ 'mailfetcher''mailsender''mailparserself-test code is in selftest py to allow mailconfig' path to be set before running thr nested module imports above mailtool class example - contains common superclasses for the other classes in the package this is in part meant for future expansion at presentthese are used only to enable or disable trace message output (some clientssuch as web-based programsmay not want text to be printed to the output streamsubclasses mix in the silent variant to turn off output client-side scripting
5,526
""##############################################################################common superclassesused to turn trace massages on/off ##############################################################################""class mailtooldef trace(selfmessage)print(messagesuperclass for all mail tools redef me to disable or log to file class silentmailtooldef trace(selfmessage)pass to mixin instead of subclassing mailsender class the class used to compose and send messages is coded in example - this module provides convenient interface that combines standard library tools we've already met in this -the email package to compose messages with attachments and encodingsand the smtplib module to send the resulting email text attachments are passed in as list of filenames--mime types and any required encodings are determined automatically with the module mimetypes moreoverdate and time strings are automated with an email utils calland non-ascii headers are encoded per emailmimeand unicode standards study this file' code and comments for more on its operation unicode issues for attachmentssave filesand headers this is also where we open and add attachment filesgenerate message textand save sent messages to local file most attachment files are opened in binary modebut as we've seensome text attachments must be opened in text mode because the current email package requires them to be str strings when message objects are created as we also saw earlierthe email package requires attachments to be str text when mail text is later generatedpossibly as the result of mime encoding to satisfy these constraints with the python email packagewe must apply the two fixes described earlier-part file open calls select between text or binary mode (and thus read str or bytesbased upon the way email will process the dataand mime encoding calls for binary data are augmented to decode the result to ascii text the latter of these also splits the base text into lines here for binary parts (unlike email)because it is otherwise sent as one long linewhich may work in some contextsbut causes problems in some text editors if the raw text is viewed beyond these fixesclients may optionally provide the names of the unicode encoding scheme associated with the main text part and each text attachment part in ' pymailguithis is controlled in the mailconfig user settings modulewith utf- used as fallback default whenever user settings fail to encode text part we the mailtools utility package
5,527
(as we do for received mails in the mail fetcher ahead)but sending an invalid attachment is much more grievous than displaying one insteadthe send request fails entirely on errors finallythere is also new support for encoding non-ascii headers (both full headers and names of email addressesper client-selectable encoding that defaults to utf- and the sent message save file is opened in the same mailconfig unicode encoding mode used to decode messages when they are fetched the latter policy for sent mail saves is used because the sent file may be opened to fetch full mail text in this encoding later by clients which apply this encoding scheme this is intended to mirror the way that clients such as pymailgui save full message text in local files to be opened and parsed later it might fail if the mail fetcher resorted to guessing different and incompatible encodingand it assumes that no message gives rise to incompatibly encoded data in the file across multiple sessions we could instead keep one save file per encodingbut encodings for full message text probably will not varyascii was the original standard for full mail textso or -bit text is likely example - pp \internet\email\mailtools\mailsender py ""##############################################################################send messagesadd attachments (see __init__ for docstest##############################################################################""import mailconfig import smtplibosmimetypes import email utilsemail encoders from mailtool import mailtoolsilentmailtool client' mailconfig mimename to type date stringbase epackage-relative from email message import message from email mime multipart import mimemultipart from email mime audio import mimeaudio from email mime image import mimeimage from email mime text import mimetext from email mime base import mimebase from email mime application import mimeapplication general messageobj->text type-specific messages format/encode attachments euse new app class def fix_encode_base (msgobj)"" eworkaround for genuine bug in python email package that prevents mail text generation for binary parts encoded with base or other email encodingsthe normal email encoder run by the constructor leaves payload as byteseven though it' encoded to base text formthis breaks email text generation which assumes this is text and requires it to be strnet effect is that only simple text part emails can be composed in py email package as is any mime-encoded binary part cause mail text generation to failthis bug seems likely to go away in future python and email packagein which case this should become no-opsee for more details client-side scripting
5,528
linelen per mime standards from email encoders import encode_base encode_base (msgobjtext msgobj get_payload(if isinstance(textbytes)text text decode('ascii'what email does normallyleaves bytes bytes fails in email pkg on text gen payload is bytes in str in alpha decode to unicode str so text gen works lines [split into lineselse massive line text text replace('\ '''no \ present in but futureproof mewhile textlinetext text[:linelen]text[linelen:lines append(linemsgobj set_payload('\njoin(lines)def fix_text_required(encodingname)"" eworkaround for str/bytes combination errors in email packagemimetext requires different types for different unicode encodings in python due to the different ways it mime-encodes some types of textsee the only other alternative is using generic message and repeating much code""from email charset import charsetbase qp charset charset(encodingnamebodyenc charset body_encoding return bodyenc in (noneqphow email knows what to do for encoding utf others require bytes input data asciilatin others require str class mailsender(mailtool)""send mailformat messageinterface with an smtp serverworks on any machine with python+inetdoesn' use cmdline maila nonauthenticating clientsee mailsenderauth if login required etracesize is num chars of msg text traced =nonebig=all esupports unicode encodings for main text and text parts esupports header encodingboth full headers and email names""def __init__(selfsmtpserver=nonetracesize= )self smtpservername smtpserver or mailconfig smtpservername self tracesize tracesize def sendmessage(selffromtosubjextrahdrsbodytextattachessavemailseparator=(('= 'py\ ')bodytextencoding='us-ascii'attachesencodings=none)""format and send mailblocks callerthread me in guibodytext is main text partattaches is list of filenamesextrahdrs is list of (namevaluetuples to be addedraises uncaught exception if send fails for any reasonsaves sent message text in local file if successfulthe mailtools utility package
5,529
decoded addresses (possibly in full nameformat)client must parse to split these on delimitersor use multiline inputnote that smtp allows full nameformat in recipients ebcc addrs now used for send/envelopebut header is dropped eduplicate recipients removedelse will get > copies of mailcaveatno support for multipart/alternative mailsjust /mixed"" eassume main body text is already in desired encodingclients can decode to user pickdefaultor utf fallbackeither wayemail needs either str xor bytes specificallyif fix_text_required(bodytextencoding)if not isinstance(bodytextstr)bodytext bodytext decode(bodytextencodingelseif not isinstance(bodytextbytes)bodytext bodytext encode(bodytextencodingmake message root if not attachesmsg message(msg set_payload(bodytextcharset=bodytextencodingelsemsg mimemultipart(self addattachments(msgbodytextattachesbodytextencodingattachesencodings enon-ascii hdrs encoded on sendsencode just name in addresselse smtp may drop the message completelyencodes all envelope to names (but not addralsoand assumes servers will allowmsg as_string retains any line breaks added by encoding headershdrenc mailconfig headersencodeto or 'utf- default=utf subj self encodeheader(subjhdrencfull header from self encodeaddrheader(fromhdrencemail names to [self encodeaddrheader(thdrencfor in toeach recip tos 'join(tohdr+envelope add headers to root msg['from'from msg['to'tos poss manyaddr list msg['subject'subj servers reject ';sept msg['date'email utils formatdate(curr datetimerfc utc recip to for namevalue in extrahdrsccbccx-maileretc if valueif name lower(not in ['cc''bcc']value self encodeheader(valuehdrencmsg[namevalue elsevalue [self encodeaddrheader(vhdrencfor in valuerecip +value some servers reject ['' client-side scripting
5,530
msg[name'join(valuerecip list(set(recip)fulltext msg as_string( ebcc gets mailno hdr add commas between cc eremove duplicates generate formatted msg sendmail call raises except if all tos failedor returns failed tos dict for any that failed self trace('sending to str(recip)self trace(fulltext[:self tracesize]smtp calls connect server smtplib smtp(self smtpservernamethis may fail too self getpassword(if srvr requires self authenticateserver(serverlogin in subclass tryfailed server sendmail(fromrecipfulltextexcept or dict exceptserver close( equit may hangraise reraise except elseserver quit(connect send ok self savesentmessage(fulltextsavemailseparator edo this first if failedclass someaddrsfailed(exception)pass raise someaddrsfailed('failed addrs:% \nfailedself trace('send exit'def addattachments(selfmainmsgbodytextattachesbodytextencodingattachesencodings)""format multipart message with attachmentsuse unicode encodings for text parts if passed""add main text/plain part msg mimetext(bodytext_charset=bodytextencodingmainmsg attach(msgadd attachment parts encodings attachesencodings or (['us-ascii'len(attaches)for (filenamefileencodein zip(attachesencodings)filename may be absolute or relative if not os path isfile(filename)skip dirsetc continue guess content type from file extensionignore encoding contypeencoding mimetypes guess_type(filenameif contype is none or encoding is not noneno guesscompressedcontype 'application/octet-streamuse generic default self trace('adding contypebuild sub-message of appropriate kind maintypesubtype contype split('/' if maintype ='text' etext needs encoding if fix_text_required(fileencode)requires str or bytes data open(filename' 'encoding=fileencodethe mailtools utility package
5,531
data open(filename'rb'msg mimetext(data read()_subtype=subtype_charset=fileencodedata close(elif maintype ='image'data open(filename'rb' euse fix for binaries msg mimeimagedata read()_subtype=subtype_encoder=fix_encode_base data close(elif maintype ='audio'data open(filename'rb'msg mimeaudiodata read()_subtype=subtype_encoder=fix_encode_base data close(elif maintype ='application'new in data open(filename'rb'msg mimeapplicationdata read()_subtype=subtype_encoder=fix_encode_base data close(elsedata open(filename'rb'msg mimebase(maintypesubtypemsg set_payload(data read()data close(fix_encode_base (msg#email encoders encode_base (msgapplication/could use this code too make generic type was broken here tooencode using base set filename and attach to container basename os path basename(filenamemsg add_header('content-disposition''attachment'filename=basenamemainmsg attach(msgtext outside mime structureseen by non-mime mail readers mainmsg preamble ' multi-part mime format message \nmainmsg epilogue 'make sure message ends with newline def savesentmessage(selffulltextsavemailseparator)""append sent message to local file if send worked for anyclientpass separator used for your applicationsplitscaveatuser may change the file at same time (unlikely)""trysentfile open(mailconfig sentmailfile' 'encoding=mailconfig fetchencodingif fulltext[- !'\ 'fulltext +'\nsentfile write(savemailseparatorsentfile write(fulltextsentfile close(except client-side scripting
5,532
not show-stopper def encodeheader(selfheadertextunicodeencoding='utf- ')"" eencode composed non-ascii message headers content per both email and unicode standardsaccording to an optional user setting or utf- header encode adds line breaks in header string automatically if needed""tryheadertext encode('ascii'excepttryhdrobj email header make_header([(headertextunicodeencoding)]headertext hdrobj encode(exceptpass auto splits into multiple cont lines if needed return headertext smtplib may fail if it won' encode to ascii def encodeaddrheader(selfheadertextunicodeencoding='utf- ')"" etry to encode non-ascii names in email addresess per emailmimeand unicode standardsif this fails drop name and use just addr partif cannot even get addressestry to decode as wholeelse smtplib may run into errors when it tries to encode the entire mail as asciiutf- default should work for mostas it formats code points broadlyinserts newlines if too long or hdr encode split names to multiple linesbut this may not catch some lines longer than the cutoff (improve me)as usedmessage as_string formatter won' try to break lines furthersee also decodeaddrheader in mailparser module for the inverse of this""trypairs email utils getaddresses([headertext]split addrs parts encoded [for nameaddr in pairstryname encode('ascii'use as is if okay as ascii except unicodeerrorelse try to encode name part tryuni name encode(unicodeencodinghdr email header make_header([(uniunicodeencoding)]name hdr encode(exceptname none drop nameuse address part only joined email utils formataddr((nameaddr)quote name if need encoded append(joinedfullhdr 'join(encodedif len(fullhdr or '\nin fullhdrfullhdr ',\ join(encodedreturn fullhdr exceptreturn self encodeheader(headertextnot one short linetry multiple lines def authenticateserver(selfserver)the mailtools utility package
5,533
no login required for this server/class def getpassword(self)pass no login required for this server/class ###############################################################################specialized subclasses ###############################################################################class mailsenderauth(mailsender)""use for servers that require login authorizationclientchoose mailsender or mailsenderauth super class based on mailconfig smtpuser setting (none?""smtppassword none eon classnot selfshared by poss instances def __init__(selfsmtpserver=nonesmtpuser=none)mailsender __init__(selfsmtpserverself smtpuser smtpuser or mailconfig smtpuser #self smtppassword none emakes pymailgui ask for each senddef authenticateserver(selfserver)server login(self smtpuserself smtppassworddef getpassword(self)""get smtp auth password if not yet knownmay be called by superclass autoor client manualnot needed until sendbut don' run in gui threadget from client-side file or subclass method ""if not self smtppasswordtrylocalfile open(mailconfig smtppasswdfilemailsenderauth smtppassword localfile readline()[:- self trace('local file passwordrepr(self smtppassword)exceptmailsenderauth smtppassword self asksmtppassword( def asksmtppassword(self)assert false'subclass must define methodclass mailsenderauthconsole(mailsenderauth)def asksmtppassword(self)import getpass prompt 'password for % on % ?(self smtpuserself smtpservernamereturn getpass getpass(promptclass silentmailsender(silentmailtoolmailsender)pass replaces trace client-side scripting
5,534
the class defined in example - does the work of interfacing with pop email server--loadingdeletingand synchronizing this class merits few additional words of explanation general usage this module deals strictly in email textparsing email after it has been fetched is delegated to different module in the package moreoverthis module doesn' cache already loaded informationclients must add their own mail-retention tools if desired clients must also provide password input methods or pass one inif they cannot use the console input subclass here ( guis and web-based programsthe loading and deleting tasks use the standard library poplib module in ways we saw earlier in this but notice that there are interfaces for fetching just message header text with the top action in pop if the mail server supports it this can save substantial time if clients need to fetch only basic details for an email index in additionthe header and full-text fetchers are equipped to load just mails newer than particular number (useful once an initial load is run)and to restrict fetches to fixed-sized set of the mostly recently arrived emails (useful for large inboxes with slow internet access or serversthis module also supports the notion of progress indicators--for methods that perform multiple downloads or deletionscallers may pass in function that will be called as each mail is processed this function will receive the current and total step numbers it' left up to the caller to render this in guiconsoleor other user interface unicode decoding for full mail text on fetches additionallythis module is where we apply the session-wide message bytes unicode decoding policy required for parsingas discussed earlier in this this decoding uses an encoding name user setting in the mailconfig modulefollowed by heuristics because this decoding is performed immediately when mail is fetchedall clients of this package can assume message text is str unicode strings--including any later parsingdisplayor save operations in addition to the mailconfig settingwe also apply few guesses with common encoding typesthough it' not impossible that this may lead to problems if mails decoded by guessing cannot be written to mail save fails using the mailconfig setting as describedthis session-wide approach to encodings is not idealbut it can be adjusted per client session and reflects the current limitations of email in python --its parser requires already decoded unicode stringsbut fetches return bytes if this decoding failsas last resort we attempt to decode headers onlyas either ascii (or other common formattext or the platform defaultand insert an error message in the email body-- heuristic that attempts to avoid killing clients with exceptions if possible (see the mailtools utility package
5,535
was the original requirement of email standards in principlewe could try to search for encoding information in message headers if it' presentby parsing mails partially ourselves we might then take per-message instead of per-session approach to decoding full textand associate an encoding type with each mail for later processing such as savesthough this raises further complicationsas save file can have just one (compatibleencodingnot one per message moreovercharacter sets in email headers may refer to individual componentsnot the entire email' text since most mails will conform to or -bit standardsand since future email release will likely address this issueextra complexity is probably not warranted for this case in this book also keep in mind that the unicode decoding performed here is for the entire mail text fetched from server reallythis is just one part of the email encoding story in the unicode-aware world of today in additionpayloads of parsed message parts may still be returned as bytes and require special handling or further unicode decoding (see the parser module aheadtext parts and attachments in composed mails impose encoding choices as well (see the sender module earliermessage headers have their own encoding conventionsand may be both mime and unicode encoded if internationalized (see both the parser and sender modulesinbox synchronization tools when you start studying this exampleyou'll also notice that example - devotes substantial code to detecting synchronization errors between an email list held by client and the current state of the inbox at the pop email server normallypop assigns relative message numbers to email in the inboxand only adds newly arrived emails to the end of the inbox as resultrelative message numbers from an earlier fetch may usually be used to delete and fetch in the future howeveralthough rareit is not impossible for the server' inbox to change in ways that invalidate previously fetched message numbers for instanceemails may be deleted in another clientand the server itself may move mails from the inbox to an undeliverable state on download errors (this may vary per ispin both casesemail may be removed from the middle of the inboxthrowing some prior relative message numbers out of sync with the server this situation can result in fetching the wrong message in an email client--users receive different message than the one they thought they had selected worsethis can make deletions inaccurate--if mail client uses relative message number in delete requestthe wrong mail may be deleted if the inbox has changed since the index was fetched client-side scripting
5,536
these tools are useful only to clients that retain the fetched email list as state information we'll use these in the pymailgui client in theredeletions use the safe interfaceand loads run the on-demand synchronization teston detection of synchronization errorsthe inbox index is automatically reloaded for nowsee example - source code and comments for more details note that the synchronization tests try variety of matching techniquesbut require the complete headers text andin the worst casemust parse headers and match many header fields in many casesthe single previously fetched message-id header field would be sufficient for matching against messages in the server' inbox howeverbecause this field is optional and can be forged to have any valueit might not always be reliable way to identify messages in other wordsa same-valued message-id may not suffice to guarantee matchalthough it can be used to identify mismatchin example - the message-id is used to rule out match if either message has oneand they differ in value this test is performed before falling back on slower parsing and multiple header matches example - pp \internet\email\mailtools\mailfetcher py ""##############################################################################retrievedeletematch mail from pop server (see __init__ for docstest##############################################################################""import poplibmailconfigsys print('user:'mailconfig popusernameclient' mailconfig on sys path script dirpythonpathchanges from mailparser import mailparser from mailtool import mailtoolsilentmailtool for headers matching ( etrace control supers ( eindex/server msgnum out of synch tests class deletesyncherror(exception)pass class topnotsupported(exception)pass class messagesyncherror(exception)pass msg out of synch in del can' run synch test index list out of sync class mailfetcher(mailtool)""fetch mailconnectfetch headers+mailsdelete mails works on any machine with python+inetsubclass me to cache implemented with the pop protocolimap requires new class ehandles decoding of full mail text on fetch for parser""def __init__(selfpopserver=nonepopuser=nonepoppswd=nonehastop=true)self popserver popserver or mailconfig popservername self popuser popuser or mailconfig popusername self srvrhastop hastop self poppassword poppswd ask later if none the mailtools utility package
5,537
self trace('connecting 'self getpassword(server poplib pop (self popserverserver user(self popuserserver pass_(self poppasswordself trace(server getwelcome()return server fileguior console connect,login pop server pass is reserved word print returned greeting use setting in client' mailconfig on import search pathto tailorthis can be changed in class or per instancefetchencoding mailconfig fetchencoding def decodefulltext(selfmessagebytes)"" epy decode full fetched mail text bytes to str unicode stringdone at fetchfor later display or parsing (full mail text is always unicode thereafter)decode with per-class or per-instance settingor common typescould also try headers inspectionor intelligent guess from structurein python this step may not be requiredif sochange to return message line list intactfor more details see an -bit encoding such as latin- will likely suffice for most emailsas ascii is the original standardthis method applies to entire/full message textwhich is really just one part of the email encoding storymessage payloads and message headers may also be encoded per emailmimeand unicode standardssee and mailparser and mailsender for more""text none kinds [self fetchencodingtry user setting first kinds +['ascii''latin ''utf 'then try common types kinds +[sys getdefaultencoding()and platform dflt (may differfor kind in kindsmay cause mail saves to fail trytext [line decode(kindfor line in messagebytesbreak except (unicodeerrorlookuperror)lookuperrorbad name pass if text =nonetry returning headers error msgelse except may kill clientstill try to decode headers per asciiotherplatform defaultblankline messagebytes index( ''hdrsonly messagebytes[:blanklinecommons ['ascii''latin ''utf 'for common in commonstrytext [line decode(commonfor line in hdrsonlybreak except unicodeerrorpass elsenone worked trytext [line decode(for line in hdrsonlyplatform dflt client-side scripting
5,538
text ['from(sender of unknown unicode format headers)'text +['''--sorrymailtools cannot decode this mail content!--'return text def downloadmessage(selfmsgnum)""load full raw text of one mail msggiven its pop relative msgnumcaller must parse content ""self trace('load str(msgnum)server self connect(tryrespmsglinesrespsz server retr(msgnumfinallyserver quit(msglines self decodefulltext(msglinesraw bytes to unicode str return '\njoin(msglinesconcat lines for parsing def downloadallheaders(selfprogress=noneloadfrom= )""get sizesraw header text onlyfor all or new msgs begins loading headers from message number loadfrom use loadfrom to load newly arrived mails only use downloadmessage to get full msg text later progress is function called with (counttotal)returns[headers text][mail sizes]loadedfull eadd mailconfig fetchlimit to support large email inboxesif not noneonly fetches that many headersand returns others as dummy/empty mailelse inboxes like one of mine ( emailsare not practical to use epass loadfrom along to downloadallmsgs ( buglet)""if not self srvrhastopnot all servers support top naively load full msg text return self downloadallmsgs(progressloadfromelseself trace('loading headers'fetchlimit mailconfig fetchlimit server self connect(mbox now locked until quit tryrespmsginfosrespsz server list('num sizelines list msgcount len(msginfosalt to srvr stat[ msginfos msginfos[loadfrom- :drop already loadeds allsizes [int( split()[ ]for in msginfosallhdrs [for msgnum in range(loadfrommsgcount+ )poss empty if progressprogress(msgnummsgcountrun callback if fetchlimit and (msgnum <msgcount fetchlimit)skipadd dummy hdrs hdrtext 'subject--mail skipped--\ \nallhdrs append(hdrtextelsefetchretr hdrs only the mailtools utility package
5,539
hdrlines self decodefulltext(hdrlinesallhdrs append('\njoin(hdrlines)finallyserver quit(assert len(allhdrs=len(allsizesself trace('load headers exit'return allhdrsallsizesfalse make sure unlock mbox def downloadallmessages(selfprogress=noneloadfrom= )""load full message text for all msgs from loadfrom ndespite any caching that may be being done in the callermuch slower than downloadallheadersif just need hdrs esupport mailconfig fetchlimitsee downloadallheaderscould use server list(to get sizes of skipped emails here toobut clients probably don' care about these anyhow""self trace('loading full messages'fetchlimit mailconfig fetchlimit server self connect(try(msgcountmsgbytesserver stat(inbox on server allmsgs [allsizes [for in range(loadfrommsgcount+ )empty if low >high if progressprogress(imsgcountif fetchlimit and ( <msgcount fetchlimit)skipadd dummy mail mailtext 'subject--mail skipped--\ \nmail skipped \nallmsgs append(mailtextallsizes append(len(mailtext)elsefetchretr full mail (respmessagerespszserver retr(isave text on list message self decodefulltext(messageallmsgs append('\njoin(message)leave mail on server allsizes append(respszdiff from len(msgfinallyserver quit(unlock the mail box assert len(allmsgs=(msgcount loadfrom msg nums start at #assert sum(allsizes=msgbytes not if loadfrom return allmsgsallsizestrue not if fetchlimit def deletemessages(selfmsgnumsprogress=none)""delete multiple msgs off serverassumes email inbox unchanged since msgnums were last determined/loadeduse if msg headers not available as state informationfastbut poss dangeroussee deletemessagessafely ""self trace('deleting mails'server self connect(try client-side scripting
5,540
don' reconnect for each if progressprogress(ix+ len(msgnums)server dele(msgnumfinallychanges msgnumsreload server quit(def deletemessagessafely(selfmsgnumssynchheadersprogress=none)""delete multiple msgs off serverbut use top fetches to check for match on each msg' header part before deletingassumes the email server supports the top interface of popelse raises topnotsupported client may call deletemessagesuse if the mail server might change the inbox since the email index was last fetchedthereby changing pop relative message numbersthis can happen if email is deleted in different clientsome isps may also move mail from inbox to the undeliverable box in response to failed downloadsynchheaders must be list of already loaded mail hdrs textcorresponding to selected msgnums (requires state)raises exception if any out of synch with the email serverinbox is locked until quitso it should not change between top check and actual deletesynch check must occur herenot in callermay be enough to call checksyncherror+deletemessagesbut check each msg here in case deletes and inserts in middle of inbox""if not self srvrhastopraise topnotsupported('safe delete cancelled'self trace('deleting mails safely'errmsg 'message % out of synch with server \nerrmsg +'delete terminated at this message \nerrmsg +'mail client may require restart or reload server self connect(locks inbox till quit trydon' reconnect for each (msgcountmsgbytesserver stat(inbox size on server for (ixmsgnumin enumerate(msgnums)if progressprogress(ix+ len(msgnums)if msgnum msgcountmsgs deleted raise deletesyncherror(errmsg msgnumresphdrlinesrespsz server top(msgnum hdrs only hdrlines self decodefulltext(hdrlinesmsghdrs '\njoin(hdrlinesif not self headersmatch(msghdrssynchheaders[msgnum- ])raise deletesyncherror(errmsg msgnumelseserver dele(msgnumsafe to delete this msg finallychanges msgnumsreload server quit(unlock inbox on way out def checksyncherror(selfsynchheaders)""check to see if already loaded hdrs text in synchheaders the mailtools utility package
5,541
pop to fetch headers textuse if inbox can change due to deletes in other clientor automatic action by email serverraises except if out of synchor error while talking to serverfor speedonly checks last in lastthis catches inbox deletesbut assumes server won' insert before last (true for incoming mails)check inbox size firstsmaller if just deleteselse top will differ if deletes and newly arrived messages added at endresult valid only when runinbox may change after return""self trace('synch check'errormsg 'message index out of synch with mail server \nerrormsg +'mail client may require restart or reload server self connect(trylastmsgnum len(synchheaders (msgcountmsgbytesserver stat(inbox size if lastmsgnum msgcountfewer nowraise messagesyncherror(errormsgnone to cmp if self srvrhastopresphdrlinesrespsz server top(lastmsgnum hdrs only hdrlines self decodefulltext(hdrlineslastmsghdrs '\njoin(hdrlinesif not self headersmatch(lastmsghdrssynchheaders[- ])raise messagesyncherror(errormsgfinallyserver quit(def headersmatch(selfhdrtext hdrtext )"""may not be as simple as string comparesome servers add "status:header that changes over timeon one ispit begins as "statusu(unread)and changes to "statusro(readoldafter fetched once throws off synch tests if new when index fetchedbut have been fetched once before delete or last-message check"message-id:line is unique per message in theorybut optionaland can be anything if forgedmatch more commontry firstparsing costlytry last ""try match by simple string compare if hdrtext =hdrtext self trace('same headers text'return true try match without status lines split hdrtext splitlines( split('\ ')but no final 'split hdrtext splitlines(strip [line for line in split if not line startswith('status:')strip [line for line in split if not line startswith('status:')if strip =strip self trace('same without status'return true try mismatch by message-id headers if either has one client-side scripting
5,542
msgid [line for line in split if line[: lower(='message-id:'if (msgid or msgid and (msgid !msgid )self trace('different message-id'return false try full hdr parse and common headers if msgid missing or trash tryheaders ('from''to''subject''date'tryheaders +('cc''return-path''received'msg mailparser(parseheaders(hdrtext msg mailparser(parseheaders(hdrtext for hdr in tryheadersposs multiple received if msg get_all(hdr!msg get_all(hdr)case insensdflt none self trace('diff common headers'return false all common hdrs match and don' have diff message-id self trace('same common headers'return true def getpassword(self)""get pop password if not yet known not required until go to server from client-side file or subclass method ""if not self poppasswordtrylocalfile open(mailconfig poppasswdfileself poppassword localfile readline()[:- self trace('local file passwordrepr(self poppassword)exceptself poppassword self askpoppassword(def askpoppassword(self)assert false'subclass must define method###############################################################################specialized subclasses ###############################################################################class mailfetcherconsole(mailfetcher)def askpoppassword(self)import getpass prompt 'password for % on % ?(self popuserself popserverreturn getpass getpass(promptclass silentmailfetcher(silentmailtoolmailfetcher)pass replaces trace the mailtools utility package
5,543
example - implements the last major class in the mailtools package--given the (already decodedtext of an email messageits tools parse the mail' content into message objectwith headers and decoded parts this module is largely just wrapper around the standard library' email packagebut it adds convenience tools--finding the main text part of messagefilename generation for message partssaving attached parts to filesdecoding headerssplitting address listsand so on see the code for more information also notice the parts walker hereby coding its search logic in one place as generator functionwe guarantee that all its three clients hereas well as any others elsewhereimplement the same traversal unicode decoding for text part payloads and message headers this module also provides support for decoding message headers per email standards (both full headers and names in address headers)and handles decoding per text part encodings headers are decoded according to their contentusing tools in the email packagethe headers themselves give their mime and unicode encodingsso no user intervention is required for client conveniencewe also perform unicode decoding for main text parts to convert them from bytes to str here if needed the latter main-text decoding merits elaboration as discussed earlier in this message objects (main or attachedmay return their payloads as bytes if we fetch with decode= argumentor if they are bytes to begin within other casespayloads may be returned as str we generally need to decode bytes in order to treat payloads as text in mailtools itselfstr text part payloads are automatically encoded to bytes by decode= and then saved to binary-mode files to finesse encoding issuesbut main-text payloads are decoded to str if they are bytes this main-text decoding is performed per the encoding name in the part' message header (if present and correct)the platform defaultor guess as we learned in while guis may allow bytes for displaystr text generally provides broader unicode supportfurthermorestr is sometimes needed for later processing such as line wrapping and webpage generation since this package can' predict the role of other part payloads besides the main textclients are responsible for decoding and encoding as necessary for instanceother text parts which are saved in binary mode here may require that message headers be consulted later to extract unicode encoding names for better display for example' pymailgui will proceed this way to open text parts on demandpassing message header encoding information on to pyedit for decoding as text is loaded some of the to-text conversions performed here are potentially partial solutions (some parts may lack the required headers and fail per the platform defaultsand may need to be improvedsince this seems likely to be addressed in future release of python' email packagewe'll settle for our assumptions here client-side scripting
5,544
""##############################################################################parsing and attachment extractanalysesave (see __init__ for docstest##############################################################################""import osmimetypessys import email parser import email header import email utils from email message import message from mailtool import mailtool mimemap type to name parse text to message object eheaders decode/encode eaddr header parse/decode message may be traversed epackage-relative class mailparser(mailtool)""methods for parsing message textattachments subtle thingmessage object payloads are either simple string for non-multipart messagesor list of message objects if multipart (possibly nested)we don' need to distinguish between the two cases herebecause the message walk generator always returns self firstand so works fine on non-multipart messages too ( single object is walked)for simple messagesthe message body is always considered here to be the sole part of the mailfor multipart messagesthe parts list includes the main message textas well as all attachmentsthis allows simple messages not of type text to be handled like attachments in ui ( savedopened)message payload may also be none for some oddball part types notein py text part payloads are returned as bytes for decode= and might be str otherwisein mailtoolstext is stored as bytes for file savesbut main-text bytes payloads are decoded to unicode str per mail header info or platform default+guessclients may need to convert other payloadspymailgui uses headers to decode parts saved to binary files supports fetched message header auto-decoding per its own contentboth for general headers such as subjectas well as for names in address header such as from and toclient must request this after parsebefore displayparser doesn' decode""def walknamedparts(selfmessage)""generator to avoid repeating part naming logicskips multipart headersmakes part filenamesmessage is already parsed email message message objectdoesn' skip oddball typespayload may be nonemust handle in part savessome others may warrant skips too""for (ixpartin enumerate(message walk())walk includes message fulltype part get_content_type(ix includes parts skipped the mailtools utility package
5,545
if maintype ='multipart'multipart/*container continue elif fulltype ='message/rfc ' eskip message/rfc continue skip all message/tooelsefilenamecontype self partname(partixyield (filenamecontypepartdef partname(selfpartix)""extract filename and content type from message partfilenametries content-dispositionthen content-type name paramor generates one based on mimetype guess""filename part get_filename(filename in msg hdrscontype part get_content_type(lowercase maintype/subtype if not filenamefilename part get_param('name'try content-type name if not filenameif contype ='text/plain'hardcode plain text ext ext txtelse guesses kshelseext mimetypes guess_extension(contypeif not extext binuse generic default filename 'part-% % (ixextreturn (filenamecontypedef saveparts(selfsavedirmessage)""store all parts of message as files in local directoryreturns [('maintype/subtype''filename')list for use by callersbut does not open any parts or attachments hereget_payload decodes base quoted-printableuuencoded datamail parser may give us none payload for oddball types we probably should skip overconvert to str here to be safe""if not os path exists(savedir)os mkdir(savedirpartfiles [for (filenamecontypepartin self walknamedparts(message)fullname os path join(savedirfilenamefileobj open(fullname'wb'use binary mode content part get_payload(decode= decode base ,qp,uu if not isinstance(contentbytes) eneed bytes for rb content '(no content)decode= returns bytesfileobj write(contentbut some payloads none fileobj close( enot str(contentpartfiles append((contypefullname)for caller to open return partfiles def saveonepart(selfsavedirpartnamemessage)""dittobut find and save just one part by name "" client-side scripting
5,546
os mkdir(savedirfullname os path join(savedirpartname(contypecontentself findonepart(partnamemessageif not isinstance(contentbytes) eneed bytes for rb content '(no content)decode= returns bytesopen(fullname'wb'write(contentbut some payloads none return (contypefullname enot str(contentdef partslist(selfmessage)"""return list of filenames for all parts of an already parsed messageusing same filename logic as savepartsbut do not store the part files here ""validparts self walknamedparts(messagereturn [filename for (filenamecontypepartin validpartsdef findonepart(selfpartnamemessage)""find and return part' contentgiven its nameintended to be used in conjunction with partslistwe could also mimetypes guess_type(partnameherewe could also avoid this search by saving in dict econtent may be str or bytes--convert as needed""for (filenamecontypepartin self walknamedparts(message)if filename =partnamecontent part get_payload(decode= does base ,qp,uu return (contypecontentmay be bytes text def decodedpayload(selfpartasstr=true)"" edecode text part bytes to unicode str for displayline wrapetc part is message(decode= undoes mime email encodings (base uuencodeqp)bytes decode(performs additional unicode text string decodingstries charset encoding name in message headers first (if presentand accurate)then tries platform defaults and few guesses before giving up with error string""payload part get_payload(decode= payload may be bytes if asstr and isinstance(payloadbytes)decode= returns bytes tries [enchdr part get_content_charset(try msg headers firstif enchdrtries +[enchdrtry headers first tries +[sys getdefaultencoding()same as bytes decode(tries +['latin ''utf 'try -bitincl ascii for trie in triestry utf (windows dflttrypayload payload decode(triegive it shotehbreak except (unicodeerrorlookuperror)lookuperrbad name pass elsethe mailtools utility package
5,547
return payload def findmaintext(selfmessageasstr=true)""for text-oriented clientsreturn first text part' strfor the payload of simple messageor all parts of multipart messagelooks for text/plainthen text/htmlthen text/*before deducing that there is no text to displaythis is heuristicbut covers most simplemultipart/alternativeand multipart/mixed messagescontent-type defaults to text/plain if not in simple msghandles message nesting at top level by walking instead of list scansif non-multipart but type is text/htmlreturns the html as the text with an html typecaller may open in web browserextract plain textetcif nonmultipart and not textthere is no text to displaysave/open message content in uicaveatdoes not try to concatenate multiple inline text/plain parts if any etext payloads may be bytes--decodes to str here easstr=false to get raw bytes for html file saves""try to find plain text for part in message walk()type part get_content_type(if type ='text/plain'return typeself decodedpayload(partasstrtry to find an html part for part in message walk()type part get_content_type(if type ='text/html'return typeself decodedpayload(partasstrwalk visits message if nonmultipart may be base ,qp,uu bytes to str toocaller renders html try any other text typeincluding xml for part in message walk()if part get_content_maintype(='text'return part get_content_type()self decodedpayload(partasstrpuntcould use first partbut it' not marked as text failtext '[no text to display]if asstr else '[no text to display]return 'text/plain'failtext def decodeheader(selfrawheader)"" edecode existing message header text per both email and unicode standardsaccording to its contentreturn as is if unencoded or failsclient must call this to displayparsed message object does not decodei header example'=?utf- ? ?introducing= top= values= savers?=' header example'man where did you get that =?utf- ? ?assistant= ?='decode_header handles any line breaks in header string automaticallymay return multiple parts if any substrings of hdr are encodedand returns all client-side scripting
5,548
raw-unicode-escape and enc=nonebut returns single part with enc=none that is str instead of bytes in py if the entire header is unencoded (must handle mixed types here)see for more details/examplesthe following first attempt code was okay unless any encoded substringsor enc was returned as none (raised except which returned rawheader unchanged)hdrenc email header decode_header(rawheader)[ return hdr decode(encfails if enc=noneno encoding or encoded substrs ""tryparts email header decode_header(rawheaderdecoded [for (partencin partsfor all substrings if enc =nonepart unencodedif not isinstance(partbytes)strfull hdr unencoded decoded +[partelse do unicode decode elsedecoded +[part decode('raw-unicode-escape')elsedecoded +[part decode(enc)return join(decodedexceptreturn rawheader puntdef decodeaddrheader(selfrawheader)"" edecode existing address header text per email and unicodeaccording to its contentmust parse out first part of email address to get part'"=?utf- ? ?walmart?='from will probably have just addrbut toccbcc may have manydecodeheader handles nested encoded substrings within an entire hdrbut we can' simply call it for entire hdr here because it fails if encoded name substring ends in quote instead of whitespace or endstrsee also encodeaddrheader in mailsender module for the inverse of thisthe following first attempt code failed to handle encoded substrings in nameand raised exc for unencoded bytes parts if any encoded substringsnamebytesnameenc email header decode_header(name)[ (do email+mimeif nameencname namebytes decode(nameenc(do unicode?""trypairs email utils getaddresses([rawheader]split addrs and parts decoded [handles name commas for (nameaddrin pairstryname self decodeheader(nameemail+mime+uni exceptname none but uses encooded name if exc in decodeheader joined email utils formataddr((nameaddr)join parts decoded append(joinedreturn 'join(decoded> addrs exceptreturn self decodeheader(rawheadertry decoding entire string the mailtools utility package
5,549
"" euse comma separator for multiple addrs in the uiand getaddresses to split correctly and allow for comma in the name parts of addressesused by pymailgui to split toccbcc as needed for user inputs and copied headersreturns empty list if field is emptyor any exception occurs""trypairs email utils getaddresses([field][(name,addr)return [email utils formataddr(pairfor pair in pairs[name exceptreturn 'syntax error in user-entered field?etc returned when parses fail errormessage message(errormessage set_payload('[unable to parse message format error]'def parseheaders(selfmailtext)""parse headers onlyreturn root email message message object stops after headers parsedeven if nothing else follows (topemail message message object is mapping for mail header fields payload of message object is nonenot raw body text ""tryreturn email parser parser(parsestr(mailtextheadersonly=trueexceptreturn self errormessage def parsemessage(selffulltext)""parse entire messagereturn root email message message object payload of message object is string if not is_multipart(payload of message object is more messages if multiple parts the call here same as calling email message_from_string(""tryreturn email parser parser(parsestr(fulltextmay failexceptreturn self errormessage or let call handlecan check return def parsemessageraw(selffulltext)""parse headers onlyreturn root email message message object stops after headers parsedfor efficiency (not yet used herepayload of message object is raw text of mail after headers ""tryreturn email parser headerparser(parsestr(fulltextexceptreturn self errormessage client-side scripting
5,550
the last file in the mailtools packageexample - lists the self-test code for the package this code is separate script filein order to allow for import search path manipulation--it emulates real clientwhich is assumed to have mailconfig py module in its own source directory (this module can vary per clientexample - pp \internet\email\mailtools\selftest py ""##############################################################################self-test when this file is run as program ##############################################################################""mailconfig normally comes from the client' source directory or sys pathfor testingget it from email directory one level up import sys sys path append('import mailconfig print('config:'mailconfig __file__get these from __init__ from mailtools import (mailfetcherconsolemailsendermailsenderauthconsolemailparserif not mailconfig smtpusersender mailsender(tracesize= elsesender mailsenderauthconsole(tracesize= sender sendmessage(from mailconfig myaddressto [mailconfig myaddress]subj 'testing mailtools package'extrahdrs [(' -mailer''mailtools')]bodytext 'here is my source code\ 'attaches ['selftest py']bodytextencoding='utf- 'attachesencodings=['latin- ']attaches=['monkeys jpg']to=' adddr list 'other tests to try inspect text headers verify base encoded test mime/unicode headers change mailconfig to test fetchlimit fetcher mailfetcherconsole(def status(*args)print(argshdrssizesloadedall fetcher downloadallheaders(statusfor numhdr in enumerate(hdrs[: ])print(hdrthe mailtools utility package
5,551
print(fetcher downloadmessage(num+ rstrip()'\ ''-'* last len(hdrs)- msgssizesloadedall fetcher downloadallmessages(statusloadfrom=last for msg in msgsprint(msg[: ]'\ ''-'* parser mailparser(for in [ ]try [ len(msgs)fulltext msgs[imessage parser parsemessage(fulltextctypemaintext parser findmaintext(messageprint('parsed:'message['subject']print(maintextinput('press enter to exit'pause if clicked on windows running the self-test here' run of the self-test scriptit generates lot of outputmost of which has been deleted here for presentation in this book--as usualrun this on your own for further detailsc:\pp \internet\email\mailtoolsselftest py config\mailconfig py userpp @learning-python com adding text/ -python sending to ['pp @learning-python com'content-typemultipart/mixedboundary="=============== ==mime-version frompp @learning-python com topp @learning-python com subjecttesting mailtools package datesat may : : - -mailermailtools multi-part mime format message --=============== =content-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit here is my source code --=============== =content-typetext/ -pythoncharset="us-asciimime-version content-transfer-encoding bit content-dispositionattachmentfilename="selftest py""##############################################################################self-test when this file is run as program ############################################################################## client-side scripting
5,552
more lines omitted print(maintextinput('press enter to exit'pause if clicked on windows --=============== ==-send exit loading headers connecting password for pp @learning-python com on pop secureserver netb'+ok ( ( ( ( ( ( ( load headers exit received(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net(more lines omitted load mail? load connecting '+ok received(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net(more lines omitted load mailloading full messages connecting '+ok ( ( ( ( ( received(qmail invoked from network) may : : - receivedfrom unknown (helo pismtp - prod phx secureserver net(more lines omitted parseda fiddle de dumfiddle de deeeric the half bee press enter to exit the mailtools utility package
5,553
as final email example in this and to give better use case for the mail tools module package of the preceding sectionsexample - provides an updated version of the pymail program we met earlier (example - it uses our mailtools package to access emailinstead of interfacing with python' email package directly compare its code to the original pymail in this to see how mailtools is employed here you'll find that its mail download and send logic is substantially simpler example - pp \internet\email\pymail py #!/usr/local/bin/python ""###############################################################################pymail simple console email interface client in pythonthis version uses the mailtools packagewhich in turn uses poplibsmtpliband the email package for parsing and composing emailsdisplays first text part of mailsnot the entire full textfetches just mail headers initiallyusing the top commandfetches full text of just email selected to be displayedcaches already fetched mailscaveatno way to refresh indexuses standalone mailtools objects they can also be used as superclasses###############################################################################""import mailconfigmailtools from pymail import inputmessage mailcache {def fetchmessage( )tryfulltext mailcache[iexcept keyerrorfulltext fetcher downloadmessage(imailcache[ifulltext return fulltext def sendmessage()fromtosubjtext inputmessage(sender sendmessage(fromtosubj[]textattaches=nonedef deletemessages(todeleteverify=true)print('to be deleted:'todeleteif verify and input('delete?')[: not in [' '' ']print('delete cancelled 'elseprint('deleting messages from server 'fetcher deletemessages(todeletedef showindex(msglistmsgsizeschunk= )count for (msgsizein zip(msglistmsgsizes)email message messageint count + iter ok here print('% :\ % bytes(countsize)for hdr in ('from''to''date''subject') client-side scripting
5,554
if count chunk = input('[press enter key]'pause after each chunk def showmessage(imsglist)if < <len(msglist)fulltext fetchmessage(imessage parser parsemessage(fulltextctypemaintext parser findmaintext(messageprint('- print(maintext rstrip('\ 'main text partnot entire mail print('- and not any attachments after elseprint('bad message number'def savemessage(imailfilemsglist)if < <len(msglist)fulltext fetchmessage(isavefile open(mailfile' 'encoding=mailconfig fetchencodingsavefile write('\nfulltext '-'* '\ 'elseprint('bad message number' def msgnum(command)tryreturn int(command split()[ ]exceptreturn - assume this is bad helptext ""available commandsi index display nlist all messages (or just message nd nmark all messages for deletion (or just message ns nsave all messages to file (or just message nm compose and send new mail message quit pymail display this help text ""def interact(msglistmsgsizesmailfile)showindex(msglistmsgsizestodelete [while truetrycommand input('[pymailaction(ildsmq?'except eoferrorcommand 'qif not commandcommand '*if command =' 'break quit elif command[ =' 'showindex(msglistmsgsizesindex the mailtools utility package
5,555
list if len(command= for in range( len(msglist)+ )showmessage(imsglistelseshowmessage(msgnum(command)msglistelif command[ =' 'save if len(command= for in range( len(msglist)+ )savemessage(imailfilemsglistelsesavemessage(msgnum(command)mailfilemsglistelif command[ =' 'mark for deletion later if len(command= needs list()iter todelete list(range( len(msglist)+ )elsedelnum msgnum(commandif ( <delnum <len(msglist)and (delnum not in todelete)todelete append(delnumelseprint('bad message number'elif command[ =' 'send new mail via smtp trysendmessage(exceptprint('error mail not sent'elif command[ ='?'print(helptextelseprint('what-type "?for commands help'return todelete def main()global parsersenderfetcher mailserver mailconfig popservername mailuser mailconfig popusername mailfile mailconfig savemailfile parser sender fetcher mailtools mailparser(mailtools mailsender(mailtools mailfetcherconsole(mailservermailuserdef progress(imax)print( 'of'maxhdrslistmsgsizesignore fetcher downloadallheaders(progressmsglist [parser parseheaders(hdrtextfor hdrtext in hdrslistprint('[pymail email client]'todelete interact(msglistmsgsizesmailfile client-side scripting
5,556
if __name__ ='__main__'main(running the pymail console client this program is used interactivelythe same as the original in factthe output is nearly identicalso we won' go into further details here' quick look at this script in actionrun this on your own machine to see it firsthandc:\pp \internet\emailpymail py userpp @learning-python com loading headers connecting password for pp @learning-python com on pop secureserver netb'+ok of of of of of of of load headers exit [pymail email client bytes from =>lutz@rmi net to =>pp @learning-python com date =>wed may : : - (edtsubject => ' lumberjackand ' okay bytes from =>lutz@learning-python com to =>pp @learning-python com date =>wed may : : - subject =>testing bytes from =>eric the half bee@yahoo com to =>pp @learning-python com date =>thu may : : - subject => bytes from =>eric the half bee@aol com to =>nobody in particular@marketing com date =>thu may : : - subject => bytes from =>pp @learning-python com to =>maillist date =>thu may : : - subject =>test interactive smtplib [press enter key bytes from =>cardinal@hotmail com to =>pp @learning-python com date =>fri may : : - the mailtools utility package
5,557
bytes from =>pp @learning-python com to =>pp @learning-python com date =>sat may : : - subject =>testing mailtools package [pymailaction(ildsmq? load connecting '+ok here is my source code [pymailaction(ildsmq? [pymailaction(ildsmq? fromlutz@rmi net topp @learning-python com subjtest pymail send type message textend with line=run awayrun awaysending to ['pp @learning-python com'fromlutz@rmi net topp @learning-python com subjecttest pymail send datesat may : : - run awayrun awaysend exit [pymailaction(ildsmq? to be deleted[ delete? deleting messages from server deleting mails connecting '+ok the messages in our mailbox have quite few origins now--isp webmail clientsbasic smtp scriptsthe python interactive command linemailtools self-test codeand two console-based email clientsin later we'll add even more all their mails look the same to our scripthere' verification of the email we just sent (the second fetch finds it already in-cache) :\pp \internet\emailpymail py userpp @learning-python com loading headers connecting more lines omitted [press enter key bytes from =>cardinal@hotmail com to =>pp @learning-python com client-side scripting
5,558
=>fri may : : - subject =>among our weapons are these bytes from =>lutz@rmi net to =>pp @learning-python com date =>sat may : : - subject =>test pymail send [pymailaction(ildsmq? load connecting '+ok run awayrun away[pymailaction(ildsmq? run awayrun away[pymailaction(ildsmq? study pymail ' code for more insights as you'll seethis version eliminates some complexitiessuch as the manual formatting of composed mail message text it also does better job of displaying mail' text--instead of blindly listing the full mail text (attachments and all)it uses mailtools to fetch the first text part of the message the messages we're using are too simple to show the differencebut for mail with attachmentsthis new version will be more focused about what it displays moreoverbecause the interface to mail is encapsulated in the mailtools package' modulesif it ever must changeit will only need to be changed in that moduleregardless of how many mail clients use its tools and because the code in mailtools is sharedif we know it works for one clientwe can be sure it will work in anotherthere is no need to debug new code on the other handpymail doesn' really leverage much of the power of either mail tools or the underlying email package it uses for examplethings like attachmentsinternationalized headersand inbox synchronization are not handled at alland printing of some decoded main text may contain character sets incompatible with the console terminal interface to see the full scope of the email packagewe need to explore larger email systemsuch as pymailgui or pymailcgi the first of these is the topic of the next and the second appears in firstthoughlet' quickly survey handful of additional client-side protocol tools nntpaccessing newsgroups so far in this we have focused on python' ftp and email processing tools and have met handful of client-side scripting modules along the wayftplibpoplibsmtplibemailmimetypesurlliband so on this set is representative of python' nntpaccessing newsgroups
5,559
but it' not at all complete more or less comprehensive list of python' internet-related modules appears at the start of the previous among other thingspython also includes client-side support libraries for internet newstelnethttpxml-rpcand other standard protocols most of these are analogous to modules we've already met--they provide an object-based interface that automates the underlying sockets and message structures for instancepython' nntplib module supports the client-side interface to nntp-the network news transfer protocol--which is used for reading and posting articles to usenet newsgroups on the internet like other protocolsnntp runs on top of sockets and merely defines standard message protocollike other modulesnntplib hides most of the protocol details and presents an object-based interface to python scripts we won' get into full protocol details herebut in briefnntp servers store range of articles on the server machineusually in flat-file database if you have the domain or ip name of server machine that runs an nntp server program listening on the nntp portyou can write scripts that fetch or post articles from any machine that has python and an internet connection for instancethe script in example - by default fetches and displays the last articles from python' internet newsgroupcomp lang pythonfrom the news rmi net nntp server at one of my isps example - pp \internet\other\readnews py ""fetch and print usenet newsgroup posting from comp lang python via the nntplib modulewhich really runs on top of socketsnntplib also supports posting new messagesetc noteposts not deleted after they are read""listonly false showhdrs ['from''subject''date''newsgroups''lines'tryimport sys servernamegroupnameshowcount sys argv[ :showcount int(showcountexceptservername nntpconfig servername assign this to your server groupname 'comp lang pythoncmd line args or defaults showcount show last showcount posts connect to nntp server print('connecting to'servername'for'groupnamefrom nntplib import nntp connection nntp(servername(replycountfirstlastnameconnection group(groupnameprint('% has % articles% -% (namecountfirstlast)get request headers only fetchfrom str(int(last(showcount- ) client-side scripting
5,560
show headersget message hdr+body for (idsubjin subjects[-showcount:if fetch all hdrs print('article % [% ](idsubj)if not listonly and input('=display?'in [' '' ']replynumtidlist connection head(idfor line in listfor prefix in showhdrsif line[:len(prefix)=prefixprint(line[: ]break if input('=show body?'in [' '' ']replynumtidlist connection body(idfor line in listprint(line[: ]print(print(connection quit()as for ftp and email toolsthe script creates an nntp object and calls its methods to fetch newsgroup information and articlesheader and body text the xhdr methodfor exampleloads selected headers from range of messages for nntp servers that require authenticationyou may also have to pass usernamea passwordand possibly reader-mode flag to the nntp call see the python library manual for more on other nntp parameters and object methods in the interest of space and timei'll omit this script' outputs here when runit connects to the server and displays each article' subject linepausing to ask whether it should fetch and show the article' header information lines (headers listed in the variable showhdrs onlyand body text we can also pass this script an explicit server namenewsgroupand display count on the command line to apply it in different ways with little more workwe could turn this script into full-blown news interface for instancenew articles could be posted from within python script with code of this form (assuming the local file already contains proper nntp header lines)to postsay this (but only if you really want to post!connection nntp(servernamelocalfile open('filename'file has proper headers connection post(localfilesend text to newsgroup connection quit(we might also add tkinter-based gui frontend to this script to make it more usablebut we'll leave such an extension on the suggested exercise heap (see also the pymailgui interface' suggested extensions at the end of the next -email and news messages have similar structurenntpaccessing newsgroups
5,561
python' standard library (the modules that are installed with the interpreteralso includes client-side support for http--the hypertext transfer protocol-- message structure and port standard used to transfer information on the world wide web in shortthis is the protocol that your web browser ( internet explorerfirefoxchromeor safariuses to fetch web pages and run applications on remote servers as you surf the web essentiallyit' just bytes sent over port to really understand http-style transfersyou need to know some of the server-side scripting topics covered in ( script invocations and internet address schemes)so this section may be less useful to readers with no such background luckilythoughthe basic http interfaces in python are simple enough for cursory understanding even at this point in the bookso let' take brief look here python' standard http client module automates much of the protocol defined by http and allows scripts to fetch web pages as clients much like web browsersas we'll see in http server also allows us to implement web servers to handle the other side of the dialog for instancethe script in example - can be used to grab any file from any server machine running an http web server program as usualthe file (and descriptive header linesis ultimately transferred as formatted messages over standard socket portbut most of the complexity is hidden by the http client module (see our raw socket dialog with port http server in for comparisonexample - pp \internet\other\http-getfile py ""fetch file from an http (webserver over sockets via http clientthe filename parameter may have full directory pathand may name cgi script with query parameters on the end to invoke remote programfetched file data or remote program output could be saved to local file to mimic ftpor parsed with str find or html parser modulealsohttp client request(methodurlbody=nonehdrs={})""import syshttp client showlines tryservernamefilename sys argv[ :cmdline argsexceptservernamefilename 'learning-python com''/index htmlprint(servernamefilenameserver http client httpconnection(servernameserver putrequest('get'filenameserver putheader('accept''text/html'server endheaders(connect to http site/server send request and headers post requests work here too as do cgi script filenames reply server getresponse(read reply headers data if reply status ! means success print('error sending request'reply statusreply reasonelse client-side scripting
5,562
reply close(for line in data[:showlines]print(linefile obj for data received show lines with eoln at end to savewrite data to file line already has \nbut bytes desired server names and filenames can be passed on the command line to override hardcoded defaults in the script you need to know something of the http protocol to make the most sense of this codebut it' fairly straightforward to decipher when run on the clientthis script makes an http object to connect to the serversends it get request along with acceptable reply typesand then reads the server' reply much like raw email message textthe http server' reply usually begins with set of descriptive header linesfollowed by the contents of the requested file the http object' getfile method gives us file object from which we can read the downloaded data let' fetch few files with this script like all python client-side scriptsthis one works on any machine with python and an internet connection (here it runs on windows clientassuming that all goes wellthe first few lines of the downloaded file are printedin more realistic applicationthe text we fetch would probably be saved to local fileparsed with python' html parser module (introduced in )and so on without argumentsthe script simply fetches the html index page at -python coma domain name host at commercial service providerc:\pp \internet\otherhttp-getfile py learning-python com /index html '\nb\nb'\nb"mark lutz' python training services\nb'<link rel="stylesheettype="text/csshref="_themes/blends/blen '\nnotice that in python the fetched data comes back as bytes strings againnot strsince the python html parser html parse we'll meet in expects str text strings instead of bytesyou'll likely need to resolve unicode encoding choice here in order to parsemuch the same as we did for email message text earlier in this as therewe might decode from bytes to str per defaultuser preferences or selectionsheaders inspectionor byte structure analysis because sockets send raw byteswe confront this choice point whenever data shipped over them is text in natureunless that text' type is known or always simple in formunicode implies extra steps we can also list server and file to be fetched on the command lineif we want to be more specific in the following codewe use the script to fetch files from two different websites by listing their names on the command lines ( 've truncated some of these lines so they fit in this booknotice that the filename argument can include an arbitrary remote directory path to the desired fileas in the last fetch herec:\pp \internet\otherhttp-getfile py www python org /index html www python org /index html '<!doctype html public "-// //dtd xhtml transitional//en"httpaccessing websites
5,563
'\nb'<html xmlns=" '\nb'\nc:\pp \internet\otherhttp-getfile py www python org index html www python org index html error sending request bad request :\pp \internet\otherhttp-getfile py www rmi net /~lutz www rmi net /~lutz error sending request moved permanently :\pp \internet\otherhttp-getfile py www rmi net /~lutz/index html www rmi net /~lutz/index html '\nb'\nb'\nb"mark lutz' book support site\nb'\nb'\nnotice the second and third attempts in this codeif the request failsthe script receives and displays an http error code from the server (we forgot the leading slash on the secondand the "index htmlon the third--required for this server and interfacewith the raw http interfaceswe need to be precise about what we want technicallythe string we call filename in the script can refer to either simple static web page file or server-side program that generates html as its output those serverside programs are usually called cgi scripts--the topic of and for nowkeep in mind that when filename refers to scriptthis program can be used to invoke another program that resides on remote server machine in that casewe can also specify parameters (called query stringto be passed to the remote program after herefor instancewe pass language=python parameter to cgi script we will meet in (to make this workwe also need to first spawn locally running http web server coded in python using script we first met in and will revisit in )in different window :\pp \internet\webwebserver py webdir "port :\pp \internet\otherhttp-getfile py localhost /cgi-bin/languages py?language=python localhost /cgi-bin/languages py?language=python 'languages\nb'syntax\nb'python\nbprint('hello world'\ client-side scripting
5,564
'\nthis book has much more to say later about htmlcgi scriptsand the meaning of the http get request used in example - (along with postone of two way to format information sent to an http server)so we'll skip additional details here suffice it to saythoughthat we could use the http interfaces to write our own web browsers and build scripts that use websites as though they were subroutines by sending parameters to remote programs and parsing their resultswebsites can take on the role of simple in-process functions (albeitmuch more slowly and indirectlythe urllib package revisited the http client module we just met provides low-level control for http clients when dealing with items available on the webthoughit' often easier to code downloads with python' standard urllib request moduleintroduced in the ftp section earlier in this since this module is another way to talk httplet' expand on its interfaces here recall that given urlurllib request either downloads the requested object over the net to local file or gives us file-like object from which we can read the requested object' contents as resultthe script in example - does the same work as the http client script we just wrote but requires noticeably less code example - pp \internet\other\http-getfile-urllib py ""fetch file from an http (webserver over sockets via urlliburllib supports httpftpfilesand https via url address stringsfor httpthe url can name file or trigger remote cgi scriptsee also the urllib example in the ftp sectionand the cgi script invocation in later files can be fetched over the net with python in many ways that vary in code and server requirementsover socketsftphttpurlliband cgi outputscaveatshould run filename through urllib parse quote to escape properly unless hardcoded--see later ""import sys from urllib request import urlopen showlines tryservernamefilename sys argv[ :cmdline argsexceptservernamefilename 'learning-python com''/index htmlremoteaddr 'print(remoteaddrremotefile urlopen(remoteaddrremotedata remotefile readlines(remotefile close(for line in remotedata[:showlines]print(linecan name cgi script too returns input file object read data directly here bytes with embedded \ the urllib package revisited
5,565
this version works in almost the same way as the http client version we wrote firstbut it builds and submits an internet url address to get its work done (the constructed url is printed as the script' first output lineas we saw in the ftp section of this the urllib request function urlopen returns file-like object from which we can read the remote data but because the constructed urls begin with "the urllib request module automatically employs the lower-level http interfaces to download the requested file instead of ftpc:\pp \internet\otherhttp-getfile-urllib py '\nb\nb'\nb"mark lutz' python training services\nb'<link rel="stylesheettype="text/csshref="_themes/blends/blen '\nc:\pp \internet\otherhttp-getfile-urllib py www python org /index '<!doctype html public "-// //dtd xhtml transitional//en" '\nb'\nb'<html xmlns=" '\nb'\nc:\pp \internet\otherhttp-getfile-urllib py www rmi net /~lutz '\nb'\nb'\nb"mark lutz' book support site\nb'\nb'\nc:\pp \internet\otherhttp-getfile-urllib py localhost /cgi-bin/languages py?language=java 'languages\nb'syntax\nb'java\nbsystem out println("hello world")\nb'\nb'\nas beforethe filename argument can name simple file or program invocation with optional parameters at the endas in the last run here if you read this output carefullyyou'll notice that this script still works if you leave the "index htmloff the end of site' root filename (in the third command line)unlike the raw http version of the preceding sectionthe url-based interface is smart enough to do the right thing client-side scripting
5,566
one last mutationthe following urllib request downloader script uses the slightly higher-level urlretrieve interface in that module to automatically save the downloaded file or script output to local file on the client machine this interface is handy if we really mean to store the fetched data ( to mimic the ftp protocolif we plan on processing the downloaded data immediatelythoughthis form may be less convenient than the version we just metwe need to open and read the saved file moreoverwe need to provide an extra protocol for specifying or extracting local filenameas in example - example - pp \internet\other\http-getfile-urllib py ""fetch file from an http (webserver over sockets via urlllibthis version uses an interface that saves the fetched data to local binary-mode filethe local filename is either passed in as cmdline arg or stripped from the url with urllib parsethe filename argument may have directory path at the front and query parameters at endso os path split is not enough (only splits off directory path)caveatshould urllib parse quote filename unless known ok--see later ""import sysosurllib requesturllib parse showlines tryservernamefilename sys argv[ : first cmdline argsexceptservernamefilename 'learning-python com''/index htmlremoteaddr 'any address on the net if len(sys argv= get result filename localname sys argv[ else(schemeserverpathparmsqueryfragurllib parse urlparse(remoteaddrlocalname os path split(path)[ print(remoteaddrlocalnameurllib request urlretrieve(remoteaddrlocalnameremotedata open(localname'rb'readlines(for line in remotedata[:showlines]print(linecan be file or script saved to local file file is bytes/binary let' run this last variant from command line its basic operation is the same as the last two versionslike the prior oneit builds urland like both of the last twowe can list an explicit target server and file path on the command linec:\pp \internet\otherhttp-getfile-urllib py '\nb\nb'\nb"mark lutz' python training services\nb'<link rel="stylesheettype="text/csshref="_themes/blends/blen '\nthe urllib package revisited
5,567
'<!doctype html public "-// //dtd xhtml transitional//en" '\nb'\nb'<html xmlns=" '\nb'\nbecause this version uses urllib request interface that automatically saves the downloaded data in local fileit' similar to ftp downloads in spirit but this script must also somehow come up with local filename for storing the data you can either let the script strip and use the base filename from the constructed urlor explicitly pass local filename as last command-line argument in the prior runfor instancethe downloaded web page is stored in the local file index html in the current working directory--the base filename stripped from the url (the script prints the url and local filename as its first output linein the next runthe local filename is passed explicitly as py-index htmlc:\pp \internet\otherhttp-getfile-urllib py www python org /index html py-index html '<!doctype html public "-// //dtd xhtml transitional//en" '\nb'\nb'<html xmlns=" '\nb'\nc:\pp \internet\otherhttp-getfile-urllib py www rmi net /~lutz books html '\nb'\nb'\nb"mark lutz' book support site\nb'\nb'\nc:\pp \internet\otherhttp-getfile-urllib py www rmi net /~lutz/about-pp html '\nb'\nb'\nb'about "programming python"\nb'\nb'\ninvoking programs and escaping text the next listing shows this script being used to trigger remote program as beforeif you don' give the local filename explicitlythe script strips the base filename out of the filename argument that' not always easy or appropriate for program client-side scripting
5,568
query parameters at the end for remote program invocation given script invocation url and no explicit output filenamethe script extracts the base filename in the middle by using first the standard urllib parse module to pull out the file pathand then os path split to strip off the directory path howeverthe resulting filename is remote script' nameand it may or may not be an appropriate place to store the data locally in the first run that followsfor examplethe script' output goes in local file called languages pythe script name in the middle of the urlin the secondwe instead name the output cxxsyntax html explicitly to suppress filename extractionc:\pp \internet\otherpython http-getfile-urllib py localhost /cgi-bin/languages py?language=scheme 'languages\nb'syntax\nb'scheme\nb(display "hello world"(newline\nb'\nb'\nc:\pp \internet\otherpython http-getfile-urllib py localhost /cgi-bin/languages py?language= +cxxsyntax html 'languages\nb'syntax\nb' \nb"sorry-- don' know that language\nb'\nb'\nthe remote script returns not-found message when passed " ++in the last command here it turns out that "+is special character in url strings (meaning space)and to be robustboth of the urllib scripts we've just written should really run the filename string through something called urllib parse quotea tool that escapes special characters for transmission we will talk about this in depth in so consider this preview for now but to make this invocation workwe need to use special sequences in the constructed url here' how to do it by handc:\pp \internet\otherpython http-getfile-urllib py localhost /cgi-bin/languages py?language= % % cxxsyntax html 'languages\nb'syntax\nb' ++\nbcout &lt;&lt"hello world&lt;&ltendl\nb'\nb'\nthe odd % strings in this command line are not entirely magicalthe escaping required for urls can be seen by running standard python tools manually--this is what these the urllib package revisited
5,569
urllib parse unquote can undo these escapes if neededc:\pp \internet\otherpython import urllib parse urllib parse quote(' ++'' % % bagaindon' work too hard at understanding these last few commandswe will revisit urls and url escapes in while exploring server-side scripting in python will also explain there why the +result came back with other oddities like &lt;&lt;--html escapes for <<generated by the tool cgi escape in the script on the server that produces the replyand usually undone by html parsers including python' html parser module we'll meet in import cgi cgi escape('<<''&lt;&lt;also in we'll meet urllib support for proxiesand its support for clientside cookies we'll discuss the related https concept in --http transmissions over secure socketssupported by urllib request on the client side if ssl support is compiled into your python for nowit' time to wrap up our look at the weband the internet at largefrom the client side of the fence other client-side scripting options in this we focused on client-side interfaces to standard protocols that run over socketsbut as suggested in an earlier footnoteclient-side programming can take other formstoo we outlined many of these at the start of --web service protocols (including soap and xml-rpc)rich internet application toolkits (including flexsilverlightand pyjamas)cross-language framework integration (including java and net)and more as mentionedmost of these serve to extend the functionality of web browsersand so ultimately run on top of the http protocol we explored in this for instancethe jython systema compiler that supports python-coded java applets--generalpurpose programs downloaded from server and run locally on the client when accessed or referenced by urlwhich extend the functionality of web browsers and interactions similarlyrias provide ajax communication and widget toolkits that allow javascript to implement user interaction within web browserswhich is more dynamic and rich than html and web browsers otherwise support in we'll also study python' support for xml--structured text that is used as the data transfer medium of client/server dialogs in web service protocols such as xml-rpcwhich transfer xml-encoded objects over httpand are client-side scripting
5,570
in deference to time and spacethoughwe won' go into further details on these and other client-side tools here if you are interested in using python to script clientsyou should take few minutes to become familiar with the list of internet tools documented in the python library reference manual all work on similar principles but have slightly distinct interfaces in we'll hop the fence to the other side of the internet world and explore scripts that run on server machines such programs give rise to the grander notion of applications that live entirely on the web and are launched by web browsers as we take this leap in structurekeep in mind that the tools we met in this and the preceding are often sufficient to implement all the distributed processing that many applications requireand they can work in harmony with scripts that run on server to completely understand the web worldviewthoughwe need to explore the server realmtoo before we get therethoughthe next puts concepts we've learned here to work by presenting complete client-side program-- full-blown mail client guiwhich ties together many of the tools we've learned and coded in factmuch of the email work we've done in this was designed to lay the groundwork we'll need to tackle the realistically scaled pymailgui example of the next reallymuch of this book so far has served to build up skills required to equip us for this taskas we'll seepymailgui combines system toolsguisand client-side internet protocols to produce useful system that does real work as an added bonusthis example will help us understand the trade-offs between the client solutions we've met here and the serverside solutions we'll study later in this part of the book other client-side scripting options
5,571
the pymailgui client "use the sourcelukethe preceding introduced python' client-side internet protocols tool set--the standard library modules available for emailftpnetwork newshttpand morefrom within python script this picks up where the last one left off and presents complete client-side example--pymailguia python program that sendsreceivescomposesand parses internet email messages although the end result is working program that you can actually use for your emailthis also has few additional agendas worth noting before we get startedclient-side scripting pymailgui implements full-featured desktop gui that runs on your machine and communicates with your mail servers when necessary as suchit is network client program that further illustrates some of the preceding topicsand it will help us contrast server-side solutions introduced in the next code reuse additionallypymailgui ties together number of the utility modules we've been writing in the book so farand it demonstrates the power of code reuse in the process--it uses thread module to allow mail transfers to overlap in timea set of mail modules to process message content and route it across networksa window protocol module to handle iconsa text editor componentand so on moreoverit inherits the power of tools in the python standard librarysuch as the email packagemessage construction and parsingfor exampleis nearly trivial here programming in the large and finallythis serves to illustrate realistic and large-scale software development in action because pymailgui is relatively large and complete programit shows by example some of the code structuring techniques that prove useful once we leave the realm of the small and artificial for instanceobjectoriented programming and modular design work well here to divide the system in smallerself-contained units
5,572
guisnetworkingand python can take us like all python programsthis system is scriptable--once you've learned its general structureyou can easily change it to work as you likeby modifying its source code and like all python programsthis one is portable--you can run it on any system with python and network connectionwithout having to change its code such advantages become automatic when your software is coded in an open sourceportableand readable language like python source code modules and size this is something of self-study exercise because pymailgui is fairly large and mostly applies concepts we've already learnedwe won' go into much detail about its actual code insteadit is listed for you to read on your own encourage you to study the source and comments and to run this program live to get feel for its operationexample save-mail files are included so you can even experiment offline as you study and run this programyou'll also want to refer back to the modules we introduced earlier in the book and are reusing hereto gain full understanding of the system for referencehere are the major examples that will see new action in this example - pp internet email mailtools (packageserver sends and receivesparsingconstruction (client-side scripting example - pp gui tools threadtools py thread queue management for gui callbacks (gui tools example - pp gui tools windows py border configuration for top-level window (gui tools example - pp gui texteditor texteditor py text widget used in mail view windowsand in some pop ups (gui examples some of these modules in turn use additional examples we coded earlier but that are not imported by pymailgui itself (texteditorfor instanceuses guimaker to create its windows and toolbarnaturallywe'll also be coding new modules here the following new modules are intended to be potentially useful in other programspopuputil py various pop-up windowswritten for general use messagecache py cache manager that keeps track of mail already loaded wraplines py utility for wrapping long lines of messages mailconfig py user configuration parameters--server namesfontsand so on (augmented here the pymailgui client
5,573
rudimentary parser for extracting plain text from html-based emails finallythe following are the new major modules coded in this which are specific to the pymailgui program in totalpymailgui itself consists of the ten modules in this and the preceding listsalong with handful of less prominent source files we'll see in this sharednames py program-wide globals used by multiple files viewwindows py the implementation of viewwritereplyand forward message view windows listwindows py the implementation of mail-server and local-file message list windows pymailguihelp py user-oriented help textopened by the main window' bar button pymailgui py the maintop-level file of the programrun to launch the main window code size as realistically scaled systempymailgui' size is also instructive all toldpymailgui is composed of new filesthe new python modules in the two preceding listsplus an html help filea small configuration file for pyedit pop upsa currently unused package initialization fileand short python files in subdirectory used for alternate account configuration togetherit contains some , new lines of program source code in python files (including comments and whitespace)plus roughly , lines of help text in one python and one html file (in two flavorsthis , new line total doesn' include the four other book examples listed in the previous section that are reused in pymailgui the reused examples themselves constitute , additional lines of python program code--roughly , lines each for pyedit and mailtools alone that brings the grand total to , lines , new , reused of this total , lines is in program code files ( , of which are new hereand , lines is help text obtained these lines counts with pyedit' info pop upand opened the files with the code button in the pydemos entry for this program (the source button in pymailgui' and rememberyou would have to multiply these line counts by factor of four or more to get the equivalent in language like or +if you've done much programmingyou probably recognize that the fact that we can implement fairly full-featured mail processing program in roughly , total lines of program code speaks volumes about the power of the python language and its libraries for comparisonthe original version of this program from the second edition of this book was just total lines in new modulesbut it also was very limited--it did not support pymailgui ' attachmentsthread overlaplocal mail filesand so onand did not have the internationalization support or other features of this edition' pymailgui "use the sourceluke
5,574
filessee the excel spreadsheet file linecounts xls in the media subdirectory of pymailguithis file is also used to test attachment sends and receivesand so appears near the end of the emails in file savedemail\version - if opened in the gui (we'll see how to open mail save files in momentwatch for the changes section ahead for size comparisons to prior versions also see the sloc counter script in for an alternative way to count source lines that is less manualbut can' include all related files in single run and doesn' discriminate between program code and help text code structure as these statistics probably suggestthis is the largest example we'll see in this bookbut you shouldn' be deterred by its size because it uses modular and oop techniquesthe code is simpler than you may thinkpython' modules allow us to divide the system into files that have cohesive purposewith minimal coupling between them--code is easier to locate and understand if your modules have logicalself-contained structure python' oop support allows us to factor code for reuse and avoid redundancy-as you'll seecode is customizednot repeatedand the classes we will code reflect the actual components of the gui to make them easy to follow for instancethe implementation of mail list windows is easy to read and changebecause it has been factored into common shared superclasswhich is customized by subclasses for mail-server and save-file listssince these are mostly just variations on thememost of the code appears in just one place similarlythe code that implements the message view window is superclass shared by writereplyand forward composition windowssubclasses simply tailor it for writing rather than viewing although we'll deploy these techniques in the context of mail processing program heresuch techniques will apply to any nontrivial program you'll write in python to help get you startedthe pymailguihelp py module listed in part near the end of this includes help text string that describes how this program is usedas well as its major features you can also view this help live in both text and html form when the program is run experimenting with the systemwhile referring to its codeis probably the best and quickest way to uncover its secrets why pymailguibefore we start digging into the code of this relatively large systemsome context is in order pymailgui is python program that implements client-side email processing user interface with the standard tkinter gui toolkit it is presented both as an instance the pymailgui client
5,575
tools we've already seensuch as threads and tkinter guis like the pymail console-based program we wrote in pymailgui runs entirely on your local computer your email is fetched from and sent to remote mail servers over socketsbut the program and its user interface run locally as resultpymailgui is called an email clientlike pymailit employs python' client-side tools to talk to mail servers from the local machine unlike pymailthoughpymailgui is full-featured user interfaceemail operations are performed with point-and-click operations and advanced mail processing such as attachmentssave filesand internationalization is supported like many examples presented in this textpymailgui is practicaluseful program in facti run it on all kinds of machines to check my email while traveling around the world teaching python classes although pymailgui won' put microsoft outlook out of business anytime soonit has two key pragmatic features alluded to earlier that have nothing to do with email itself--portability and scriptabilitywhich are attractive features in their own right and merit few additional words hereit' portable pymailgui runs on any machine with sockets and python with tkinter installed because email is transferred with the python librariesany internet connection that supports post office protocol (popand simple mail transfer protocol (smtpaccess will do moreoverbecause the user interface is coded with tkinterpymailgui should workunchangedon windowsthe window system (unixlinux)and the macintosh (classic and os )as long as python runs there too microsoft outlook may be more feature-rich packagebut it has to be run on windowsand more specificallyon single windows machine because it generally deletes email from server as it is downloaded by default and stores it on the clientyou cannot run outlook on multiple machines without spreading your email across all those machines by contrastpymailgui saves and deletes email only on requestand so it is bit friendlier to people who check their email in an ad hoc fashion on arbitrary computers (like meit' scriptable pymailgui can become anything you want it to be because it is fully programmable in factthis is the real killer feature of pymailgui and of open source software like python in general--because you have full access to pymailgui' source codeyou are in complete control of where it evolves from here you have nowhere near as much control over commercialclosed products like outlookyou generally get whatever large company decided you needalong with whatever bugs that company might have introduced as python scriptpymailgui is much more flexible tool for instancewe can change its layoutdisable featuresand add completely new functionality quickly by changing its python source code don' like the mail-list displaychange few "use the sourceluke
5,576
it is loadedadd some more code and buttons tired of seeing junk mailadd few lines of text processing code to the load function to filter spam these are just few examples the point is that because pymailgui is written in high-leveleasy-to-maintain scripting languagesuch customizations are relatively simpleand might even be fun at the end of the daybecause of such featuresthis is realistic python program that actually use--both as primary email tool and as fallback option when my isp' webmail system goes down (whichas mentioned in the prior has way of happening at the worst possible timespython scripting is an enabling skill to have running pymailgui of courseto script pymailgui on your ownyou'll need to be able to run it pymailgui requires only computer with some sort of internet connectivity ( pc with broadband or dial-up account will doand an installed python with the tkinter extension enabled the windows port of python has this capabilityso windows pc users should be able to run this program immediately by clicking its icon two notes on running the systemfirstyou'll want to change the file mailconfig py in the program' source directory to reflect your account' parametersif you wish to send or receive mail from live servermore on this as we interact with the system ahead secondyou can still experiment with the system without live internet connection-for quick look at message view windowsuse the main window' open buttons to open saved-mail files included in the program' savedmail subdirectory the pydemos launcher script at the top of the book' examples directoryfor exampleforces pymailgui to open saved-mail files by passing filenames on the command line although you'll probably want to connect to your email servers eventuallyviewing saved mails offline is enough to sample the system' flavor and does not require any configuration file changes presentation strategy pymailgui is easily the largest program in this bookbut it doesn' introduce many library interfaces that we haven' already seen in this book for instancethe pymailgui interface is built with python' tkinterusing the familiar listboxesbuttonsand text widgets we met earlier python' email package is applied to pull-out headerstextand attachments of messagesand to compose the same in factmy isp' webmail send system went down the very day had to submit the third edition of this book to my publisherno worries-- fired up pymailgui and used it to send the book as attachment files through different server in sensethis book submitted itself the pymailgui client
5,577
over sockets python threadsif installed in your python interpreterare put to work to avoid blocking during potentially overlappinglong-running mail operations we're also going to reuse the pyedit texteditor object we wrote in to view and compose messages and to pop up raw textattachmentsand sourcethe mail tools package' tools we wrote in to loadsendand delete mail with serverand the mailconfig module strategy introduced in to support enduser settings pymailgui is largely an exercise in combining existing tools on the other handbecause this program is so longwe won' exhaustively document all of its code insteadwe'll begin with quick look at how pymailgui has evolvedand then move on to describing how it works today from an end user' perspective- brief demo of its windows in action after thatwe'll list the system' new source code modules without many additional commentsfor further study like most of the longer case studies in this bookthis section assumes that you already know enough python to make sense of the code on your own if you've been reading this book linearlyyou should also know enough about tkinterthreadsand mail interfaces to understand the library tools applied here if you get stuckyou may wish to brush up on the presentation of these topics earlier in the book major pymailgui changes like the pyedit text editor of pymailgui serves as good example of software evolution in action because its revisions help document this system' functionalityand because this example is as much about software engineering as about python itselflet' take quick look at its recent changes new in version and (third editionthe version of pymailgui presented in the third edition of the book in early is still largely present and current in this fourth edition in version added handful of enhancements to version and version was complete rewrite of the version of the second edition with radically expanded feature set in factthe second edition' version of this program written in early was only some total program lines long ( lines for the gui main script and lines in an email utilities module)not counting related examples reusedand just lines in its help text module version was really something of prototype (if not toy)written mostly to serve as short book example although it did not yet support internationalized mail content or other extensionsin the third editionpymailgui became much more realistic and feature-rich program that could be used for day-to-day email processing it grew by nearly factor major pymailgui changes
5,578
modules reusedand additional lines of help textby comparisonversion by itself grew only by some to be , new program source lines as described earlier (plus , lines in related modulesand , lines of help textstatistically minded readersconsult file linecounts-prior-version xls in pymailgui' media subdirectory for line counts breakdown for version by file in version among pymailgui' new weapons were (and still arethesemime multipart mails with attachments may be both viewed and composed mail transfers are no longer blockingand may overlap in time mail may be saved and processed offline from local file message parts may now be opened automatically within the gui multiple messages may be selected for processing in list windows initial downloads fetch mail headers onlyfull mails are fetched on request view window headers and list window columns are configurable deletions are performed immediatelynot delayed until program exit most server transfers report their progress in the gui long lines are intelligently wrapped in viewed and quoted text fonts and colors in list and view windows may be configured by the user authenticating smtp mail-send servers that require login are supported sent messages are saved in local filewhich may be opened in the gui view windows intelligently pick main text part to be displayed already fetched mail headers and full mails are cached for speed date strings and addresses in composed mails are formatted properly view windows now have quick-access buttons for attachments/parts ( inbox out-of-sync errors are detected on deletesand on index and mail loads ( save-mail file loads and deletes are threadedto avoid pauses for large files ( the last three items on this list were added in version the rest were part of the rewrite some of these changes were made simple by growth in standard library tools ( support for attachments is straightforward with the new email package)but most represented changes in pymailgui itself there were also few genuine fixesaddresses were parsed more accuratelyand date and time formats in sent mails became standards conformingbecause these tasks used new tools in the email package new in version (fourth editionpymailgui version presented in this fourth edition of this bookinherits all of ' upgrades described in the prior section and adds many of its own changes are perhaps less dramatic in version though some address important usability issuesand they the pymailgui client
5,579
here' summary of what' new this time aroundpython port the code was updated to run under python onlypython is no longer supported without code changes although some of the task of porting to python requires only minor coding changesother idiomatic implications are more far reaching python ' new unicode focusfor examplemotivated much of the internationalization support in this version of pymailgui (discussed aheadlayout improvements view window forms are laid out with gridding instead of packed column framesfor better appearance and platform neutrality of email headers (see for more details on form layoutin additionlist window toolbars are now arranged with expanding separators for claritythis effectively groups buttons by their roles and scope list windows are also larger when initially opened to show more text editor fix for tk change both the embedded text editor and some text editor instances popped up on demand are now forcibly updated before new text is insertedfor accurate initial positioning at line see pyedit in for more on this requirementit stems from recent change (bug?in either tk or tkinter text editor upgrades inherited because the pyedit program is reused in multiple roles herethis version of pymailgui also acquires all its latest fixes by proxy most prominentlythese include new grep external files search dialog and support for displayingopeningand saving unicode text see for details workaround for python bug on traceback prints in the obscure-but-all-too-typical categorythe common function in sharednames py that prints traceback details had to be changed to work correctly under python the traceback module' print_tb function can no longer print stack trace to sys stdout if the calling program is spawned from another on windowsit still can as before if the caller was run normally from shell prompt since this function is called from the main thread on worker thread exceptionsif allowed to fail any printed error kills the gui entirely when it is spawned from the gadget or demo launchers to work around thisthe function now catches exceptions when print_tb is called and in response runs it again with real file instead of sys stdout this appears to be python regressionas the same code worked correctly in both contexts in python and unlike some similar issuesit has nothing to do with printing unicodeas stack traces are all ascii text even more bafflingdirectly printing to stdout in the same function works fine heyif it were easythey wouldn' call it "work major pymailgui changes
5,580
minor changeaddresses entered in the user-selectable bcc header line of edit windows are included in the recipients list (the "envelope")but the bcc header line itself is no longer included in the message text sent otherwisebcc recipients might be seen by some email readers and clients (including pymailgui)which defeats most of this header' purpose avoiding parallel fetches of the same mail pymailgui loads only mail headers initiallyand fetches mail' full text later when needed for viewing and other operationsallowing multiple fetches to overlap in time (they are run in parallel threadsthough unlikelyit was not impossible for user to trigger new fetch for mail that was currently being fetchedby selecting the mail again during its download (clicking its list entry twice quickly sufficed to kick this offalthough the message cache updates performed in the parallel fetch threads appeared to be thread safethis behavior seemed odd and wasted time to do betterthis version now keeps track of all fetches in progress in the main threadto avoid this overlap potential entirely-- message fetch in progress disables all new fetch requests that it is part ofuntil its fetch completes multiple overlapping fetches are still allowedas long as their targets do not intersect set is used to detect nondisjoint fetch requests mails already fetched and cached are not subject to this check and can always be selected irrespective of any fetches in progress multiple recipients separated in gui by commasnot semicolons in the prior edition";was used as the recipient characterand addresses were naively split on ";on send this attempted to avoid conflicts with ",commonly used in email names replies dropped the name part if it contained ";when extracting to addressbut it was not impossible that clashes could still arise if ";appeared both as the separator and in manually typed address' name to improvethis edition uses ",as the recipient separatorand fully parses email address lists with the email package' getaddresses and parseaddr toolsinstead of splitting naively because these tools fully parse the list' content",characters embedded in email address name parts are not mistakenly takes as address separatorsand so do not clash servers and clients generally expect ",separatorstooso this works naturally with this fixcommas can appear both as address separators as well as embedded in address name components for repliesthis is handled automaticallythe to field is prefilled with the from in the original message for sendsthe split happens automatically in email tools for toccand bcc headers fields (the latter two are ignored if they contain just the initial "?when senthtml help display help can now be displayed in text form in gui windowin html form in locally running web browseror both user settings in the mailconfig module select which form or forms to display the html version is newit uses simple the pymailgui client
5,581
python' webbrowser modulediscussed earlier in this bookto open browser the text help display is now redundantbut it is retained because the html display currently lacks its ability to open source file viewers thread callback queue speedup the global thread queue dispatches gui update callbacks much faster now--up to times per secondinstead of the prior this is due both to checking more frequently ( timer events per second versus and to dispatching more callbacks per timer event ( versus the prior depending on the interleaving of queue puts and getsthis speeds up initial loads for larger mailboxes by as much as an order of magnitude (factor of )at some potential minor cost in cpu utilization on my windows laptopthoughpymailgui still shows cpu utilization in task manager when idle bumped up the queue' speed to support an email account having , inbox messages (actuallyeven more by the time got around to taking screenshots for this without the speedupinitial header loads for this account took minutes to work through the , progress callbacks ( )even though most reflected messages skipped immediately by the new mail fetch limits (see the next itemwith the speedupthe initial load takes just seconds-perhaps not ideal stillbut this initial headers load is normally performed only once per sessionand this policy strikes balance between cpu resources and responsiveness this email account is an arguably pathological caseof coursebut most initial loads benefit from the faster speed see ' threadtools for most of this change' codeas well as additional background details we could alternatively loop through all queued events on each timer eventbut this may block the gui indefinitely if updates are queued quickly mail fetch limits since pymailgui loads only mail headers initiallynot full mail textand only loads newly arrived headers thereafter depending on your internet and server speedsthoughthis may still be impractical for very large inboxes (as mentionedone of mine currently has some , emailsto support such casesa new mail config setting can be used to limit the number of headers (or full mails if top is unsupportedfetched on loads given this setting npymailgui fetches at most of the most recently arrived mails older mails outside this set are not fetched from the serverbut are displayed as empty/dummy emails which are mostly inoperative (though they can generally still be fetched on demandthis feature is inherited from mailtools code in see the mailconfig module ahead for the user setting associated with it note that even with this fixbecause the threadtools queue system used here dispatches gui events such as progress updates only up to times per seconda , mail inbox still takes major pymailgui changes
5,582
stillor should delete an email once in whilehtml main text extraction (prototypepymailgui is still somewhat plain-text biaseddespite the emergence of html emails in recent years when the main (or onlytext part of mail is htmlit is displayed in popped-up web browser in the prior versionthoughits html text was still displayed in pyedit text editor component and was still quoted for the main text of replies and forwards because most people are not html parsersthis edition' version attempts to do better by extracting plain text from the part' html with simple html parsing step the extracted plain text is then displayed in the mail view window and used as original text in replies and forwards this html parser is at best prototype and is largely included to provide first step that you can tailor for your tastes and needsbut any result it produces is better than showing raw html if this fails to render the plain text wellusers can still fall back on viewing in the web browser and cutting and pasting from there into replies and forwards see also the note about open source alternatives by this parser' source code later in this this is an already explored problem domain reply copies all original recipients by default in this versionreplies are really reply-to-all by default--they automatically prefill the cc header in the replies composition window with all the original recipients of the message to do soreplies extract all addresses among both the original to and cc headersand remove duplicates as well as the new sender' address by using set operations the net effect is to copy all other recipients on the reply this is in addition to replying to the sender by initializing to with the original sender' address this feature is intended to reflect common usageemail circulated among groups since it might not always be desirablethoughit can be disabled in mailconfig so that replies initialize just to headers to reply to the original sender only if enabledusers may need to delete the cc prefill if not wantedif disabledusers may need to insert cc addresses manually instead both cases seem equally likely moreoverit' not impossible that the original recipients include mail list namesaliasesor spurious addresses that will be either incorrect or irrelevant when the reply is sent like the bcc prefill described in the next itemthe reply' cc initialization can be edited prior to sends if neededand disabled entirely if preferred also see the suggested enhancements for this feature at the end of this -allowing this to be enabled or disabled in the gui per message might be better approach other upgradesbcc prefills"reand "fwdcaselist sizeduplicate recipients in additionthere have been smaller enhancements throughout among thembcc headers in edit windows are now prefilled with the sender' address as convenience ( common role for this header)reply and forward now ignore case when the pymailgui client
5,583
list window width and height may now be configured in mailconfigduplicates are removed from the recipient address list in mailtools on sends to avoid sending anyone multiple copies of the same mail ( if an address appears in both to and cc)and other minor improvements which won' cover here look for " and " ein program comments here and in the underlying mailtools package of to see other specific code changes unicode (internationalizationsupport 've saved the most significant pymailgui upgrade for lastit now supports unicode encoding of fetchedsavedand sent mailsto the extent allowed by the python email package both text parts of messages and message headers are decoded when displayed and encoded when sent since this is too large change to explain in this formatthe next section elaborates version unicode support policies the last item on the preceding list is probably the most substantial per user-configurable setting in the mailconfig module is used on session-wide basis to decode full message bytes into unicode strings when fetchedand to encode and decode mail messages stored in text-mode save files more visiblywhen composingthe main text and attached text parts of composed mails may be given explicit unicode encodings in mailconfig or via user inputwhen viewingmessage header information of parsed emails is used to determine the unicode types of both the main mail text as well as text parts opened on demand in additioninternationalized mail headers ( subjecttoand fromare decoded per emailmimeand unicode standards when displayed according to their own contentand are automatically encoded if non-ascii when sent other unicode policies (and fixesof ' mailtools package are inherited heretoosee the prior for more details in summationhere is how all these policies play out in terms of user interfacesfetched emails when fetching mailsa session-wide user setting is used to decode full message bytes to unicode stringsas required by python' current email parserif this failsa handful of guesses are applied most mail text will likely be or bit in naturesince original email standards required ascii composed text parts when sending new mailsuser settings are used to determine unicode type for the main text part and any text attachment parts if these are not set in mailconfigthe user will instead be asked for encoding names in the gui for each text part these are ultimately used to add character set headersand to invoke mime encoding in all casesthe program falls back on utf- if the user' encoding setting or input does not work for the text being sent--for instanceif the user has chosen ascii major pymailgui changes
5,584
attachments composed headers when sending new mailsif header lines or the name component of an email address in address-related lines do not encode properly as ascii textwe first encode the header per email internationalization standard this is done per utf- by defaultbut mailconfig setting can request different encoding in email address pairsnames which cannot be encoded are droppedand only the email address is used it is assumed that servers will respect the encoded names in email addresses displayed text parts when viewing fetched mailunicode encoding names in message headers are used to decode whenever possible the main-text part is decoded into str unicode text per header information prior to inserting it into pyedit component the content of all other text partsas well as all binary partsis saved in bytes form in binarymode filesfrom where the part may be opened later in the gui on demand when such on-demand text parts are openedthey are displayed in pyedit pop-up windows by passing to pyedit the name of the part' binary-mode fileas well as the part' encoding name obtained from part message headers if the encoding name in text part' header is absent or fails to decodeencoding guesses are tried for main-text partsand pyedit' separate unicode policies are applied to text parts opened on demand (see --it may prompt for an encoding if not knownin addition to these ruleshtml text parts are saved in binary mode and opened in web browserrelying on the browser' own character set supportthis may in turn use tags in the html itselfguessesor user encoding selections displayed headers when viewing emailmessage headers are automatically decoded per email standards this includes both full headers such as subjectas well as the name components of all email address fields in address-related headers such as fromtoand ccand allows these components to be completely encoded or contain encoded substrings because their content gives their mime and unicode encodingsno user interaction is required to decode headers in other wordspymailgui now supports internationalized message display and composition for both payloads and headers for broadest utilitythis support is distributed across multiple packages and examples for exampleunicode decoding of full message text on fetches actually occurs deep in the imported mailtool package classes because of thisfull (unparsedmessage text is always unicode str here similarlyheaders are decoded for display here using tools implemented in mailtoolsbut headers encoding is both initiated and performed within mailtools itself on sends full text decoding illustrates the types of choices required it is done according to the fetchencoding variable in the mailconfig module this user setting is used across an the pymailgui client
5,585
to parsingand to save and load full message text to save files users may set this variable to unicode encoding name string which works for their mailsencodings"latin- ""utf- "and "asciiare reasonable guesses for most emailsas email standards originally called for ascii (though "latin- was required to decode some old mail save files generated by the prior versionif decoding with this encoding name failsother common encodings are attemptedand as last resort the message is still displayed if its headers can be decodedbut its body is changed to an error messageto view such unlikely mailstry running pymailgui again with different encoding in the negatives columnnothing is done about the unicode format for the full text of sent mailsapart from that inherited from python' libraries (as we learned in smtplib attempts to encode per ascii when messages are sentwhich is one reason that header encoding is requiredand while mail content character sets are fully supportedthe gui itself still uses english for its labels and buttons as explained in this program' unicode polices are broad but partial solutionbecause the email package in python upon which pymailgui utterly relies for correct operationis in state of flux for some use cases an updated version which handles the python str/bytes distinctions more accurately and completely is likely to appear in the futurewatch this book' updates page (see the prefacefor future changes and improvements to this program' unicode policies hopefullythe current email package underlying pymailgui will be available for some time to come although there is still room for improvement (see the list at the end of this the pymailgui program is able to provide full-featured email interfacerepresents the most substantial example in this bookand serves to demonstrate realistic application of the python language and software engineering at large as its users often attestpython may be fun to work withbut it' also useful for writing practical and nontrivial software this examplemore than any other in this booktestifies the same the next section shows how pymailgui demo pymailgui is multiwindow interface it consists of the followinga main mail-server list window opened initiallyfor online mail processing one or more mail save-file list windows for offline mail processing one or more mail-view windows for viewing and editing messages pyedit windows for displaying raw mail textextracted text partsand the system' source code nonblocking busy state pop-up dialogs assorted pop-up dialogs for opened message partshelpand more pymailgui demo
5,586
one for each active server transferand one for each active offline save file load or deletion pymailgui supports mail save filesautomatic saves of sent messagesconfigurable fonts and colorsviewing and adding attachmentsmain message text extractionplain text conversion for htmland much more to make this case study easier to understandlet' begin by seeing what pymailgui actually does--its user interaction and email processing functionality--before jumping into the python code that implements that behavior as you read this partfeel free to jump ahead to the code listings that appear after the screenshotsbut be sure to read this sectiontoothisalong with the prior discussion of version changesis where some subtleties of pymailgui' design are explained after this sectionyou are invited to study the system' python source code listings on your own for better and more complete explanation than can be crafted in english getting started okit' time to take the system out for test drive ' going to run the following demo on my windows laptop it may look slightly different on different platforms (including other versions of windowsthanks to the gui toolkit' native-look-and-feel supportbut the basic functionality will be similar pymailgui is python/tkinter programrun by executing its top-level script filepymailgui py like other python programspymailgui can be started from the system command lineby clicking on its filename icon in file explorer interfaceor by pressing its button in the pydemos or pygadgets launcher bar however it is startedthe first window pymailgui presents is captured in figure - shown after running load to fetch mail headers from my isp' email server notice the "pywindow iconthis is the handiwork of window protocol tools we wrote earlier in this book also notice the non-ascii subject lines herei'll talk about internationalization features later this is the pymailgui main window--every operation starts here it consists ofa help button (the bar at the topa clickable email list area for fetched emails (the middle sectiona button bar at the bottom for processing messages selected in the list area in normal operationusers load their emailselect an email from the list area by clicking on itand press button at the bottom to process it no mail messages are shown initiallywe need to first load them with the load button-- simple password input dialog is displayeda busy dialog appears that counts down message headers being downloaded to give status indicationand the index is filled with messages ready to be selected the pymailgui client
5,587
pymailgui' list windowssuch as the one in figure - display mail header details in fixed-width columnsup to maximum size mails with attachments are prefixed with "*in mail index list windowsand fonts and colors in pymailgui windows like this one can be customized by the user in the mailconfig configuration file you can' tell in this black-and-white bookbut most of the mail index lists we'll see are configured to be indian redview windows are light bluepop-up pyedit windows are beige instead of pyedit' normal light cyanand help is steel blue you can change most of these as you likeand pyedit pop-up window appearance can be altered in the gui itself (see example - for help with color definition stringsand watch for alternative configuration examples aheadlist windows allow multiple messages to be selected at once--the action selected at the bottom of the window is applied to all selected mails for instanceto view many mailsselect them all and press vieweach will be fetched (if neededand displayed in its own view window use the all check button in the bottom right corner to select or deselect every mail in the listand ctrl-click and shift-click combinations to select more than one (the standard windows multiple selection operations apply--try itbefore we go any furtherthoughlet' press the help bar at the top of the list window in figure - to see what sort of help is availablefigure - shows the text-based help window pop up that appears--one of two help flavors available the main part of this window is simply block of text in scrolled-text widgetalong with two buttons at the bottom the entire help text is coded as single triple-quoted string in the python program as we'll see in momenta fancier option which opens pymailgui demo
5,588
an html rendition of this text in spawned web browser is also availablebut simple text is sufficient for many people' tastes +the cancel button makes this nonmodal ( nonblockingwindow go away more interestinglythe source button pops up pyedit text editor viewer windows for all the source files of pymailgui' implementationfigure - captures one of these (there are manythis is intended as demonstrationnot as development environmentnot every program shows you its source codebut pymailgui follows python' open source motif new in this editionhelp is also displayed in html form in web browserin addition to or instead of the scrolled text display just shown choosing help in texthtmlor both is controlled by setting in the mailconfig module the html flavor uses the python webbrowser module to pop up the html file in browser on the local machine+actuallythe help display started life even less fancyit originally displayed help text in standard information pop up common dialoggenerated by the tkinter showinfo call used earlier in the book this worked fine on windows (at least with small amount of help text)but it failed on linux because of default line-length limit in information pop-up boxeslines were broken so badly as to be illegible over the yearscommon dialogs were replaced by scrolled textwhich has now been largely replaced by htmli suppose the next edition will require holographic help interface the pymailgui client
5,589
and currently lacks the source-file opening button of the text display version (one reason you may wish to display the text viewertoohtml help is captured in figure - when message is selected for viewing in the mail list window by mouse click and view presspymailgui downloads its full text (if it has not yet been downloaded in this session)and formatted email viewer window appearsas captured in figure - for an existing message in my account' inbox view windows are built in response to actions in list windows and take the following formthe top portion consists of action buttons (part to list all message partssplit to save and open parts using selected directoryand cancel to close this nonmodal window)along with section for displaying email header lines (fromtoand so onin the middlea row of quick-access buttons for opening message partsincluding attachmentsappears when clickedpymailgui opens known and generally safe parts according to their type media types may open in web browser or image viewertext parts in pyedithtml in web browserwindows document types per the windows registryand so on pymailgui demo
5,590
the bulk of this window (its entire lower portionis just another reuse of the texteditor class object of the pyedit program we wrote in --pymailgui simply attaches an instance of texteditor to every view and compose window in order to get full-featured text editor component for free in factmuch on the window shown in figure - is implemented by texteditornot by pymailgui reusing pyedit' class this way means that all of its tools are at our disposal for email text--cut and pastefind and gotosaving copy of the text to fileand so on for instancethe pyedit save button at the bottom left of figure - can be used to save just the main text of the mail (as we'll see laterclicking the leftmost part button in the middle of the screen affords similar utilityand you can also save the entire message from list windowto make this reuse even more concreteif we pick the tools menu of the text portion of this window and select its info entrywe get the standard pyedit texteditor object' text statistics box shown in figure - --the same pop up we' get in the standalone pyedit text editor and in the pyview image view programs we wrote in in factthis is the third reuse of texteditor in this bookpyeditpyviewand now pymailgui all present the same text-editing interface to userssimply because they all use the same texteditor object and code pymailgui uses it in multiple roles--it both attaches instances of this class for mail viewing and compositionand pops up instances in independent windows for some text mail partsraw message text displayand python the pymailgui client
5,591
source-code viewing (we saw the latter in figure - for mail view componentspymailgui customizes pyedit text fonts and colors per its own configuration modulefor pop upsuser preferences in local textconfig module are applied to display emailpymailgui inserts its text into an attached texteditor objectto compose emailpymailgui presents texteditor and later fetches all its text to ship over the net besides the obvious simplification herethis code reuse makes it easy to pick up improvements and fixes--any changes in the texteditor object are automatically inherited by pymailguipyviewand pyedit in the third edition' versionfor instancepymailgui supports edit undo and redojust because pyedit had gained that feature and in this fourth editionall pyedit importers also inherit its new grep file searchas well as its new support for viewing and editing text of arbitrary unicode encodings--especially useful for text parts in emails of arbitrary origin like those displayed here (see for more about pyedit' evolutionloading mail nextlet' go back to the pymailgui main server list windowand click the load button to retrieve incoming email over the pop protocol pymailgui' load function gets pymailgui demo
5,592
account parameters from the mailconfig module listed later in this so be sure to change this file to reflect your email account parameters ( server names and usernamesif you wish to use pymailgui to read your own email unless you can guess the book' email account passwordthe presets in this file won' work for you the account password parameter merits few extra words in pymailguiit may come from one of two placeslocal file if you put the name of local file containing the password in the mailconfig modulepymailgui loads the password from that file as needed pop up dialog if you don' put password filename in mailconfig (or if pymailgui can' load it from the file for whatever reason)pymailgui will instead ask you for your password anytime it is needed figure - shows the password input prompt you get if you haven' stored your password in local file note that the password you type is not shown-- show='*option for the entry field used in this pop up tells tkinter to echo typed characters as stars (this option is similar in spirit to both the getpass console input module we met earlier in the prior and an html type=password option we'll meet in later once enteredthe password lives only in memory on your machinepymailgui itself doesn' store it anywhere in permanent way the pymailgui client
5,593
also notice that the local file password option requires you to store your password unencrypted in file on the local client computer this is convenient (you don' need to retype password every time you check email)but it is not generally good idea on machine you share with othersof courseleave this setting blank in mailconfig if you prefer to always enter your password in pop up once pymailgui fetches your mail parameters and somehow obtains your passwordit will next attempt to pull down just the header text of all your incoming email from your inbox on your pop email server on subsequent loadsonly newly arrived mails are loadedif any to support obscenely large inboxes (like one of mine)the program is also now clever enough to skip fetching headers for all but the last batch of messageswhose size you can configure in mailconfig--they show up early in the mail list with subject line "--mail skipped--"see the changes overview earlier for more details to save timepymailgui fetches message header text only to populate the list window the full text of messages is fetched later only when message is selected for viewing or processingand then only if the full text has not yet been fetched during this session pymailgui reuses the load-mail tools in the mailtools module of to fetch message header textwhich in turn uses python' standard poplib module to retrieve your email threading model now that we're downloading mailsi need to explain the juggling act that pymailgui performs to avoid becoming blocked and support operations that overlap in time ultimatelymail fetches run over sockets on relatively slow networks while the download is in progressthe rest of the gui remains active--you may compose and send other mails at the same timefor instance to show its progressthe nonblocking dialog of figure - is displayed when the mail index is being fetched in generalall server transfers display such dialogs figure - shows the busy dialog displayed while full text download of five selected and uncached (not yet fetchedmails is in progressin response to view action after this download finishesall five pop up in individual view windows such server transfersand other long-running operationsare run in threads to avoid blocking the gui they do not disable other actions from running in parallelas long as those actions would not conflict with currently running thread multiple mail sends and disjoint fetches can overlap in timefor instanceand can run in parallel with the pymailgui demo
5,594
figure - nonblocking progress indicatorview gui itself--the gui responds to movesredrawsand resizes during the transfers other transfers such as mail deletes must run all by themselves and disable other transfers until they are finisheddeletes update the inbox and internal caches too radically to support other parallel operations on systems without threadspymailgui instead goes into blocked state during such long-running operations (it essentially stubs out the thread-spawn operation to perform simple function callbecause the gui is essentially dead without threadscovering and uncovering the gui during mail load on such platforms will erase or otherwise distort its contents threads are enabled by default on most platforms that run python (including windows)so you probably won' see such oddness on your machine the pymailgui client
5,595
on nearly every platformthoughlong-running tasks like mail fetches and sends are spawned off as parallel threadsso that the gui remains active during the transfer--it continues updating itself and responding to new user requestswhile transfers occur in the background while that' true of threading in most guishere are two notes regarding pymailgui' specific implementation and threading modelgui updatesexit callback queue as we learned earlier in this bookonly the main thread that creates windows should generally update them see for more on thistkinter doesn' support parallel gui changes as resultpymailgui takes care to not do anything related to the user interface within threads that loadsendor delete email insteadthe main gui thread continues responding to user interface events and updatesand uses timer-based event to watch queue for exit callbacks to be added by worker threadsusing the thread tools we implemented earlier in (example - upon receiptthe main gui thread pulls the callback off the queue and invokes it to modify the gui in the main thread such queued exit callbacks can display fetched email messageupdate the mail index listchange progress indicatorreport an erroror close an email composition window--all are scheduled by worker threads on the queue but performed in the main gui thread this scheme makes the callback update actions automatically thread safesince they are run by one thread onlysuch gui updates cannot overlap in time to make this easypymailgui stores bound method objects on the thread queuewhich combine both the function to be called and the gui object itself since threads all run in the same process and memory spacethe gui object queued gives access to all gui state needed for exit updatesincluding displayed widget objects pymailgui also runs bound methods as thread actions to allow threads to update state in generaltoosubject to the next paragraph' rules other state updatesoperation overlap locks although the queued gui update callback scheme just described effectively restricts gui updates to the single main threadit' not enough to guarantee thread safety in general because some spawned threads update shared object state used by other threads ( mail caches)pymailgui also uses thread locks to prevent operations from overlapping in time if they could lead to state collisions this includes both operations that update shared objects in memory ( loading mail headers and content into caches)as well as operations that may update pop message numbers of loaded email ( deletionswhere thread overlap might be an issuethe gui tests the state of thread locksand pops up message when an operation is not currently allowed see the source code and this program' help text for specific cases where this rule is applied pymailgui demo
5,596
overlap broadlybut deletions and mail header fetches cannot in additionsome potentially long-running save-mail operations are threaded to avoid blocking the guiand this edition uses set object to prevent fetch threads for requests that include message whose fetch is in progress in order to avoid redundant work (see the changes review earlierfor more on why such things matter in generalbe sure to see the discussion of threads in guis in and pymailgui is really just concrete realization of concepts we've explored earlier load server interface let' return to loading our emailbecause the load operation is really socket operationpymailgui automatically connects to your email server using whatever connectivity exists on the machine on which it is run for instanceif you connect to the net over modem and you're not already connectedwindows automatically pops up the standard connection dialog on the broadband connections that most of us use todaythe interface to your email server is normally automatic after pymailgui finishes loading your emailit populates the main window' scrolled listbox with all of the messages on your email server and automatically scrolls to the most recently received message figure - shows what the main window looks like after selecting message with click and resizing--the text area in the middle grows and shrinks with the windowrevealing more header columns as it grows figure - pymailgui main window resized technicallythe load button fetches all your mail' header text the first time it is pressedbut it fetches only newly arrived email headers on later presses pymailgui keeps track of the last email loadedand requests only higher email numbers on later loads already loaded mail is kept in memoryin python listto avoid the cost of downloading it again pymailgui does not delete email from your server when it is the pymailgui client
5,597
delete it entries in the main list show just enough to give the user an idea of what the message contains--each entry gives the concatenation of portions of the message' subjectfromdatetoand other header linesseparated by characters and prefixed with the message' pop number ( there are emails in this listcolumns are aligned by determining the maximum size needed for any entryup to fixed maximumand the set of headers displayed can be configured in the mailconfig module use the horizontal scroll or expand the window to see additional header details such as message size and mailer as we've seena lot of magic happens when downloading email--the client (the machine on which pymailgui runsmust connect to the server (your email account machineover socket and transfer bytes over arbitrary internet links if things go wrongpymailgui pops up standard error dialog boxes to let you know what happened for exampleif you type an incorrect username or password for your account (in the mail config module or in the password pop up)you'll receive the message in figure - the details displayed here are just the python exception type and exception data additional detailsincluding stack traceshow up in standard output (the console windowon errors figure - pymailgui invalid password error box offline processing with save and open we've seen how to fetch and view emails from serverbut pymailgui can also be used in completely offline mode to save mails in local file for offline processingselect the desired messages in any mail list window and press the save action buttonas usualany number of messages may be selected for saving together as set standard file-selection dialog appearslike that in figure - and the mails are saved to the end of the chosen text file pymailgui demo
5,598
to view saved emails laterselect the open action at the bottom of any list window and pick your save file in the selection dialog new mail index list window appears for the save file and it is filled with your saved messages eventually--there may be slight delay for large save filesbecause of the work involved pymailgui runs file loads and deletions in threads to avoid blocking the rest of the guithese threads can overlap with operations on other open save-mail filesserver transfer threadsand the gui at large while mail save file is being loaded in parallel threadits window title is set to "loading as status indicationthe rest of the gui remains active during the load (you can fetch and delete server messagesview mails in other fileswrite new messagesand so onthe window title changes to the loaded file' name after the load is finished once filleda message index appears in the save file' windowlike the one captured in figure - (this window also has three mails selected for processingin generalthere can be one server mail list window and any number of save-mail file list windows open at any time save-mail file list windows like that in figure - can be opened at any timeeven before fetching any mail from the server they are identical to the server' inbox list windowbut there is no help barthe load action button is omitted since this is not server viewand all other action buttons are mapped to the save filenot to the server the pymailgui client
5,599
for exampleview opens the selected message in normal mail view window identical to that in figure - but the mail originates from the local file similarlydelete removes the message from the save fileinstead of from the server' inbox deletions from save-mail files are also run in threadto avoid blocking the rest of the gui--the window title changes to "deleting during the delete as status indicator status indicators for loads and deletions in the server inbox window use pop ups insteadbecause the wait is longer and there is progress to display (see figure - technicallysaves always append raw message text to the chosen filethe file is opened in 'amode to append textwhich creates the file if it' new and writes at its end the save and open operations are also smart enough to remember the last directory you selectedtheir file dialogs begin navigation there the next time you press save or open you can also save mails from saved file' window--use save and delete to move mails from file to file in additionsaving to file whose window is open for viewing automatically updates that file' list window in the gui this is also true for the automatically written sent-mail save filedescribed in the next section sending email and attachments once we've loaded email from the server or opened local save filewe can process our messages with the action buttons at the bottom of list windows we can also send new emails at any timeeven before load or open pressing the write button in any list window (server or filegenerates mail composition windowone has been captured in figure - pymailgui demo