id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
5,600 | this window is much like the message view window we saw in figure - except there are no quick-access part buttons in the middle (this window is new mailit has fields for entering header line detailaction buttons for sending the email and managing attachment files added to it when sentand an attached texteditor object component for writing and editing the main text of the new email the pyedit text editor component at the bottom has no file menu in this rolebut it does have save button--useful for saving draft of your mail' text in file you can cut and paste this temporary copy into composition window later if needed to begin composing again from scratch pyedit' separate unicode policies apply to mail text drafts saved this way (it may ask for an encoding--see for write operationspymailgui automatically fills the from line and inserts signature text line (the last two lines shown)from your mailconfig module settings you can change these to any text you like in the guibut the defaults are filled in automatically from your mailconfig when the mail is sentan email utils call handles date and time formatting in the mailtools module in there is also new set of action buttons in the upper left herecancel closes the window (if verified)and send delivers the mail--when you press the send buttonthe text you typed into the body of this window is mailed to all the addresses you typed into the toccand bcc linesafter removing duplicatesand using python' smtplib module pymailgui adds the header fields you type as mail header lines in the sent message (exceptionbcc recipients receive the mailbut no header line is generatedto send to more than one addressseparate them with comma character in header fieldsand feel free to use full "namepairs for recipients in this maili fill in the to header with my own email address in order to send the message to myself for the pymailgui client |
5,601 | the sender' own address if this header is enabled in mailconfigthis prefill sends copy to the sender (in addition to that written to the sent-mail file)but it can be deleted if unwanted also in compose windowsthe attach button issues file selection dialog for attaching file to your messageas in figure - the parts button pops up dialog displaying files already attachedlike that in figure - when your message is sentthe text in the edit portion of the window is sent as the main message textand any attached part files are sent as attachments properly encoded according to their type figure - attachment file dialog for attach as we've seensmtplib ultimately sends bytes to server over socket since this can be long-running operationpymailgui delegates this operation to spawned threadtoo while the send thread runsa nonblocking wait window appears and the entire gui stays aliveredraw and move events are handled in the main program thread while the send thread talks to the smtp serverand the user may perform other tasks in parallelincluding other views and sends you'll get an error pop up if python cannot send message to any of the target recipients for any reasonand the mail composition window will pop up so that you can try again or save its text for later use if you don' get an error pop upeverything worked correctlyand your mail will show up in the recipientsmailboxes on their email servers pymailgui demo |
5,602 | since sent the earlier message to myselfit shows up in mine the next time press the main window' load buttonas we see in figure - figure - pymailgui main window after loading sent mail the pymailgui client |
5,603 | email now--pymailgui is smart enough to download only the one new message' header text and tack it onto the end of the loaded email list mail send operations automatically save sent mails in save file that you name in your configuration moduleuse open to view sent messages in offline mode and delete to clean up the sent mail file if it grows too large (you can also save from the sent-mail file to another file to copy mails into other save files per categoryviewing email and attachments now let' view the mail message that was sent and received pymailgui lets us view email in formatted or raw mode firsthighlight (single-clickthe mail you want to see in the main windowand press the view button after the full message text is downloaded (unless it is already cached) formatted mail viewer window like that shown in figure - appears if multiple messages are selectedthe view button will download all that are not already cached ( that have not already been fetchedand will pop up view window for each selected like all long-running operationsfull message downloads are run in parallel threads to avoid blocking figure - pymailgui view incoming mail window python' email module is used to parse out header lines from the raw text of the email messagetheir text is placed in the fields in the top right of the window the message' main text is fetched from its body and stuffed into new texteditor object for display at the window bottom pymailgui uses heuristics to extract the main text of the message to displayif there is oneit does not blindly show the entire raw text of the mail html-only mail is handled speciallybut 'll defer details on this until later in this demo pymailgui demo |
5,604 | buttons in the middle they are also listed by the parts pop up dialogand they can be saved and opened all at once with split figure - shows this window' parts list pop upand figure - displays this window' split dialog in action figure - parts dialog listing all message parts figure - split dialog selection the pymailgui client |
5,605 | directory you selectand known parts are automatically opened individual parts are also automatically opened by the row of quick-access buttons labeled with the part' filename in the middle of the view windowafter being saved to temporary directorythis is usually more convenientespecially when there are many attachments for instancefigure - shows the two image parts attached to the mail we sent open on my windows laptopin standard image viewer on that platformother platforms may open this in web browser instead click the image filenamesquick-access buttons just below the message headers in figure - to view them immediatelyor run split to open all parts at once figure - pymailgui opening image parts in viewer or browser by this pointthe photo attachments displayed in figure - have really gotten aroundthey have been mime encodedattachedand sentand then fetchedparsedand mime decoded along the waythey have moved through multiple machines-from the clientto the smtp serverto the pop serverand back to the clientcrossing arbitrary distances along the way in terms of user interactionwe attached the images to the email in figure - using the dialog in figure - before we sent the email to access them laterwe selected the email for viewing in figure - and clicked on their quick-access button in figure - pymailgui encoded the photos in base forminserted them in the email' textand later extracted and decoded it to get the original photos with python email toolsand our own code that rides above themthis all just works as expected notice how in figures - and - the main message text counts as mail parttoo--when selectedit opens in pyedit windowlike that captured in figure - pymailgui demo |
5,606 | the save button in the view window itselfthe main part is includedbecause not all mails have text part for messages that have only html for their main text partpymailgui displays plain text extracted from its html text in its own windowand opens web browser to view the mail with its html formatting againi'll say more on html-only mails later figure - main text part opened in pyedit besides images and plain textpymailgui also opens html and xml attachments in web browser and uses the windows registry to open well-known windows document types for exampledoc and docxxls and xlsxand pdf files usually openrespectivelyin wordexceland adobe reader figure - captures the response to the lp -pref html quick-access part button in figure - on my windows laptop if you inspect this screenshot closelyor run live for better lookyou'll notice that the html attachment is displayed in both web browser and pyedit windowthe latter can be disabled in mailconfigbut is on by default to give an indication of the html' encoding the quick-access buttons in the middle of the figure - view window are more direct way to open parts than split--you don' need to select save directoryand you can open just the part you want to view the split buttonthoughallows all parts to be opened in single stepallows you to choose where to save partsand supports an arbitrary number of parts files that cannot be opened automatically because of their type can be inspected in the local save directoryafter both split and quick-access button selections (pop up dialogs name the directory to use for thisafter fixed maximum number of partsthe quick-access row ends with button labeled "which simply runs split to save and open additional parts when selected figure - captures one such message in the guithis message is available in savedmail file version - if you want to view it offline-- relatively complex mailwith total parts of mixed types the pymailgui client |
5,607 | figure - view window for mail with many parts like much of pymailgui' behaviorthe maximum number of part buttons to display in view windows can be configured in the mailconfig py user settings module that setting specified eight buttons in figure - figure - shows what the same mail looks like when the part buttons setting has been changed to maximum of five the setting can be higher than eightbut at some point the buttons may become unreadable (use split insteada pymailgui demo |
5,608 | as sample of other attachmentsbehaviorfigures - and - show what happens when the sousa au and pdf buttons in figures - and - are pressed on my windows laptop the results vary per machinethe audio file opens in windows media playermp files open in itunes insteadand some platforms may open such files directly in web browser figure - an audio part opened by pymailgui besides the nicely formatted view windowpymailgui also lets us see the raw text of mail message double-click on message' entry in the main window' list to bring the pymailgui client |
5,609 | up simple unformatted display of the mail' raw text (its full text is downloaded in thread if it hasn' yet been fetched and cachedpart of the raw version of the mail sent to myself in figure - is shown in figure - in this editionraw text is displayed in pyedit pop-up window (its prior scrolled-text display is still present as an optionbut pyedit adds tools such as searchingsavesand so onthis raw text display can be useful to see special mail headers not shown in the formatted view for instancethe optional -mailer header in the raw text display identifies the program that transmitted messagepymailgui adds it automaticallyalong with standard headers like from and to other headers are added as the mail is transmittedthe received headers name machines that the message was routed through on its way to our email serverand content-type is added and parsed by python' email package in response to calls from pymailgui and reallythe raw text form is all there is to an email message--it' what is transferred from machine to machine when mail is sent the nicely formatted display of the gui' view windows simply parses out and decodes components from the mail' raw text with standard python toolsand places them in the associated fields of the display notice the base encoding text of the image file at the end of figure - for exampleit' created when senttransferred over the internetand decoded when fetched to recreate the image' original bytes quite featbut largely automatic with the code and libraries invoked email replies and forwards and recipient options in addition to reading and writing emailpymailgui also lets users forward and reply to incoming email sent from others these are both just composition operationsbut they quote the original text and prefill header lines as appropriate to reply to an emailselect its entry in the main window' list and click the reply button if reply to the pymailgui demo |
5,610 | mail just sent to myself (arguably narcissisticbut demonstrative)the mail composition window shown in figure - appears this window is identical in format to the one we saw for the write operationexcept that pymailgui fills in some parts automatically in factthe only thing 've added in this window is the first line in the text editor partthe rest is filled in by pymailguithe from line is set to your email address in your mailconfig module the to line is initialized to the original message' from address (we're replying to the original senderafter allthe subject line is set to the original message' subject lineprepended with "re:"the standard follow-up subject line form (unless it already has onein uppercase or lowercase the pymailgui client |
5,611 | the optional bcc lineif enabled in the mailconfig moduleis prefilled with the sender' addresstoosince it' often used this way to retain copy (new in this versionthe body of the reply is initialized with the signature line in mailconfigalong with the original message' text the original message text is quoted with characters and is prepended with few header lines extracted from the original message to give some context not shown in this example and new in this versiontoothe cc header in replies is also prefilled with all the original recipients of the messageby extracting addresses among the original to and cc headersremoving duplicatesand removing your address from the result in other wordsreply really is reply-to-all by default--it replies to the sender and copies all other recipients as group since the latter isn' always desirableit can be disabled in mailconfig so that replies only initialize to with the original sender you can also simply delete the cc prefill if not wantedbut you may have to add addresses to cc manually if this feature is disabled we'll see reply cc prefills at work later pymailgui demo |
5,612 | extracts all of the original message' header linesand single string replace method call does the work of adding the quotes to the original message body simply type what wish to say in reply (the initial paragraph in the mail' text areaand press the send button to route the reply message to the mailbox on my mail server again physically sending the reply works the same as sending brand-new message--the mail is routed to your smtp server in spawned send-mail threadand the send-mail wait pop up appears while the thread runs forwarding message is similar to replyingselect the message in the main windowpress the fwd buttonand fill in the fields and text area of the popped-up composition window figure - shows the window created to forward the mail we originally wrote and received after bit of editing figure - pymailgui forward compose window much like repliesforwards fill from with the sender' address in mailconfigthe original text is automatically quoted in the message body againbcc is preset initially the same as fromand the subject line is preset to the original message' subject prepended with the string "fwd:all these lines can be changed manually before sending if you wish to tailor always have to fill in the to line manuallythoughbecause forward is not direct reply--it doesn' necessarily go back to the original sender furtherthe the pymailgui client |
5,613 | they are not continuation of group discussions notice that ' forwarding this message to three different addresses (two in the toand one manually entered in the bcci' also using full "name formats for email addresses multiple recipient addresses are separated with comma (,in the toccand bcc header fieldsand pymailgui is happy to use the full address form anywhere you type an addressincluding your own in mailconfig as demonstrated by the first to recipient in figure - commas in address names don' clash with those that separate recipientsbecause address lines are parsed fully in this version when we're readythe send button in this window fires the forwarded message off to all addresses listed in these headersafter removing any duplicates to avoid sending the same recipient the same mail more than once 've now written new messagereplied to itand forwarded it the reply and forward were sent to my email addresstooif we press the main window' load button againthe reply and forward messages should show up in the main window' list in figure - they appear as messages and (the order they appear in may depend on timing issues at your serverand 've stretched this horizontally in the gui to try to reveal the to header of the last of thesefigure - pymailgui mail list after sends and load keep in mind that pymailgui runs on the local computerbut the messages you see in the main window' list actually live in mailbox on your email server machine every time we press loadpymailgui downloads but does not delete newly arrived emailsheaders from the server to your computer the three messages we just wrote ( through will also appear in any other email program you use on your account ( in outlook or in webmail interfacepymailgui does not automatically delete messages as they are downloadedbut simply stores them in your computer' memory for processing if we now select message and press viewwe see the forward message we sentas in figure - pymailgui demo |
5,614 | from there into python list from which it is displayed in factit went to three different email accounts have (the other two appear later in this demo--see figure - the third recipient doesn' appear in figure - here because it was bcc blind-copy-it receives the messagebut no header line is added to the mail itself figure - pymailgui view forwarded mail figure - shows what the forward message' raw text looks likeagaindouble-click on main window' entry to display this form the formatted display in figure - simply extracts bits and pieces out of the text shown in the raw display form one last pointer on replies and forwardsas mentionedreplies in this version reply to all original recipientsassuming that more than one means that this is continuation of group discussion to illustratefigure - shows an original message on topa forward of it on the lower leftand reply to it on the lower right the cc header in the reply has been automatically prefilled with all the original recipientsless any duplicates and the new sender' addressthe bcc (enabled herehas also been prefilled with the sender in both these are just initial settings which can be edited and removed prior to sends moreoverthe cc prefill for replies can be disabled entirely in the configuration file without itthoughyou may have to manually cut-and-paste to insert the pymailgui client |
5,615 | addresses in group mail scenarios open this version' mail save file to view this mail' behavior liveand see the suggested enhancements later for more ideas deleting email so farwe've covered every action button on list windows except for delete and the all checkbox the all checkbox simply toggles from selecting all messages at once or deselecting all (viewdeletereplyfwdand save action buttons apply to all currently selected messagespymailgui also lets us delete messages from the server permanentlyso that we won' see them the next time we access our inbox delete operations are kicked off the same way as views and savesjust press the delete button instead in typical operationi eventually delete email ' not interested inand save and delete emails that are important we met save earlier in this demo like viewsaveand other operationsdelete can be applied to one or more messages deletes happen immediatelyand like all server transfersthey are run in nonblocking thread but are performed only if you verify the operation in pop upsuch as the one shown in figure - during the deletea progress dialog like those in figures - and - provide status pymailgui demo |
5,616 | figure - pymailgui delete verification on quit by designno mail is ever removed automaticallyyou will see the same messages the next time pymailgui runs it deletes mail from your server only when you ask it toand then only if verified in the last pop up shown (this is your last chance to prevent permanent mail removalafter the deletions are performedthe mail index is updatedand the gui session continues deletions disable mail loads and other deletes while running and cannot be run in parallel with loads or other deletes already in progress because they may change pop message numbers and thus modify the mail index list (they may also modify the email the pymailgui client |
5,617 | files may be processed pop message numbers and synchronization by nowwe've seen all the basic functionality of pymailgui--enough to get you started sending and receiving simple but typical text-based messages in the rest of this demowe're going to turn our attention to some of the deeper concepts in this systemincluding inbox synchronizationhtml mailsinternationalizationand multiple account configuration since the first of these is related to the preceding section' tour of mail deletionslet' begin here though they might seem simple from an end-user perspectiveit turns out that deletions are complicated by pop' message-numbering scheme we learned about the potential for synchronization errors between the server' inbox and the fetched email list in when studying the mailtools package pymailgui uses (near example - in briefpop assigns each message relative sequential numberstarting from oneand these numbers are passed to the server to fetch and delete messages the server' inbox is normally locked while connection is held so that series of deletions can be run as an atomic operationno other inbox changes occur until the connection is closed howevermessage number changes also have some implications for the gui itself it' never an issue if new mail arrives while we're displaying the result of prior download-the new mail is assigned higher numbersbeyond what is displayed on the client but if we delete message in the middle of mailbox after the index has been loaded from the mail serverthe numbers of all messages after the one deleted change (they are decremented by oneas resultsome message numbers might no longer be valid if deletions are made while viewing previously loaded email to work around thispymailgui adjusts all the displayed numbers after delete by simply removing the entries for deleted mails from its index list and mail cache howeverthis adjustment is not enough to keep the gui in sync with the server' inbox if the inbox is modified at position other than after the endby deletions in another email client (even in another pymailgui session)or by deletions performed by the mail server itself ( messages determined to be undeliverable and automatically removed from the inboxsuch modifications outside pymailgui' scope are uncommonbut not impossible to handle these casespymailgui uses the safe deletion and synchronization tests in mailtools that module uses mail header matching to detect mail list and server inbox synchronization errors for instanceif another email client has deleted message prior to the one to be deleted by pymailguimailtools catches the problem and cancels the deletionand an error pop up like the one in figure - is displayed pymailgui demo |
5,618 | similarlyboth index list loads and individual message fetches run synchronization test in mailtoolsas well figure - captures the error generated on fetch if message has been deleted in another client since we last loaded the server index window the same error is issued when this occurs during load operationbut the first line reads "load failed figure - synchronization error after delete in another client the pymailgui client |
5,619 | inbox content by pymailgui immediately after the error pop up is dismissed this scheme ensures that pymailgui won' delete or display the wrong messagein the rare case that the server' inbox is changed without its knowledge see mailtools in for more on synchronization teststhese errors are detected and raised in mail toolsbut triggered by calls made in the mail cache manager here handling html content in email up to this pointwe've seen pymailgui' basic operation in the context of plain-text emails we've also seen it handling html part attachmentsbut not the main text of html messages todayof coursehtml is common for mail content too because the pyedit mail display deployed by pymailgui uses tkinter text widget oriented toward plain texthtml content is handled speciallyfor text/html alternative mailspymailgui displays the plain text part in its view window and includes button for opening the html rendition in web browser on demand for html-only mailsthe main text area shows plain text extracted from the html by simple parser (not the raw html)and the html is also displayed in web browser automatically in all casesthe web browser' display of international character set content in the html depends upon encoding information in tags in the htmlguessesor user feedback well-formed html parts already have "tags in their "sections which give the html' encodingbut they may be absent or incorrect we'll learn more about internationalization support in the next section figure - gives the scene when text/html alternative mail is viewedand figure - shows what happens when an html-only email is viewed the web browser in figure - was opened by clicking the html part' buttonthis is no different than the html attachment example we saw earlier for html-only messagesthoughbehavior is new herethe view window on the left in figure - reflects the results of extracting plain text from the html shown in the popped-up web browser behind it the html parser used for this is something of first-cut prototypebut any result it can give is an improvement on displaying raw html in the view window for html-only mails for simpler html mails of the sort sent by individuals instead of those sent by mass-mailing companies (like those shown here)the results are generally good in tests run to datethough time will tell how this prototype parser fares in today' unforgiving html jungle of nonstandard and nonconforming code--improve as desired pymailgui demo |
5,620 | figure - viewing html-only mails the pymailgui client |
5,621 | plain text from itbut it cannot display html directly in its own window and has no support for editing it specially these are enhancements that will have to await further attention by other programmers who may find them useful mail content internationalization support our next advanced feature is something of an inevitable consequence of the internet' success as described earlier when summarizing version changespymailgui fully supports international character sets in mail content--both text part payloads and email headers are decoded for display and encoded when sentaccording to emailmimeand unicode standards this may be the most significant change in this version of the program regrettablycapturing this in screenshots is bit of challenge and you can get better feel for how this pans out by running an open on the following included mail save fileviewing its messages in formatted and raw modesstarting replies and forwards for themand so onc:\pp \internet\email\pymailgui\savedmail\ - to sample the flavor of this support herefigure - shows the scene when this file is openedshown for variety here with one of the alternate account configurations described the next section this figure' index list window and mail view windows capture russian and chinese language messages sent to my email account (these were unsolicited email of no particular significancebut suffice as reasonable test casesnotice how both message headers and text payload parts are decoded for display in both the mail list window and the mail view windows figure - shows portions of the raw text of the two fetched messagesobtained by double-clicking their list entries (you can open these mails from the save file listed earlier if you have trouble seeing their details as shown in this booknotice how the body text is encoded per both mime and unicode conventions--the headers at the top and text at the bottom of these windows show the actual base and quoted-printable strings that must be decoded to achieve the nicely displayed output in figure - for the text partsthe information in the part' header describes its content' encoding schemes for instancecharset="gb in the content type header identifies chinese unicode character setand the transfer encoding header gives the part' mime encoding type ( base the headers are encoded per standards here as well--their content self-describes their mime and unicode encodings for examplethe header prefix =?koi - ? means russian textbase encoded pymailgui is clever enough to decode both full headers and the name fields of addresses for displaywhether they are completely encoded (as shown hereor contain just encoded substrings (as shown by other saved mails in the version - file in this example' savedmail directorya pymailgui demo |
5,622 | figure - raw text of fetched internationalized mailsheaders and body encoded as additional contextfigure - shows how these messagesmain parts appear when opened via their part buttons their content is saved as raw post-mime bytes in binary modebut the pyedit pop ups decode according to passed-in encoding names obtained the pymailgui client |
5,623 | from the raw message headers as we learned in and the underlying tkinter toolkit generally renders decoded str better than raw bytes so farwe've displayed internationalized emailsbut pymailgui allows us to send them as welland handles any encoding tasks implied by the text content figure - shows the result of running replies and forwards to the russian language emailwith the to address changed to protect the innocent headers in the view window were decoded for displayencoded when sentand decoded back again for displaytext parts in the mail body were similarly decodedencodedand re-decoded along the way and headers are also decoded within the ">quoted original text inserted at the end of the message and finallyfigure - shows portion of the raw text of the russian language reply message that appears in the lower right of the formatted view of figure - againdouble-click to see these details live notice how both headers and body text have been encoded per email and mime standards as configuredthe body text is always mime encoded to utf- when sent if it fails to encode as asciithe default setting in the mailconfig module other defaults can be used if desired and will be encoded appropriately for sendsin facttext that won' work in the full text of email is mime encoded the same way as binary parts such as images this is also true for non-internationalized character sets--the text part of message written in english with any non-ascii quotesfor examplewill be utf- and base encoded in the same way as the message in figure - and assume that the recipient' email reader will decode (any reasonable modern email client willthis allows nonascii text to be embedded in the full email text sent pymailgui demo |
5,624 | message headers are similarly encoded per utf- if they are non-ascii when sentso they will work in the full email text in factif you study this closely you'll find that the subject here was originally encoded per russian unicode scheme but is utf- now-its new representation yields the same characters (code pointswhen decoded for display in shortalthough the gui itself is still in english (its labels and the like)the content of emails displayed and sent support arbitrary character sets decoding for display is done per content where possibleusing message headers for text payloads and content for headers encoding for sends is performed according to user settings and policiesusing user settings or inputsor utf- default required mime and email header encodings are implemented in largely automatic fashion by the underlying email package not shown here are the pop-up dialogs that may be issued to prompt for text part encoding preferences on sends if so configured in mailconfigand pyedit' similar prompts under certain user configurations some of these user configurations are meant for illustration and generalitythe presets seem to work well for most scenarios 've run intobut your international mileage may vary for more detailsexperiment with the file' messages on your own and see the system' source code the pymailgui client |
5,625 | alternative configurations and accounts so farwe've mostly seen pymailgui being run on an email account created for this book' examplesbut it' easy to tailor its mailconfig module for different accountsas well as different visual effects for examplefigure - captures the scene with pymailgui being run on three different email accounts use for books and training all three instances are run in independent processes here each main list window is displaying different email account' messagesand each customizes appearance or behavior in some fashion the message view window at the topopened from the server list window in the lower left also applies custom color and displayed headers schemes you can always change mailconfigs in-place for specific account if you use just onebut we'll later see how the altconfigs subdirectory applies one possible solution to allow configuring for multiple accounts such as thesecompletely external to the original source code the altconfigs option renders the windows in figure - and suffices as my launching interfacesee its code ahead pymailgui demo |
5,626 | multiple windows and status messages finallypymailgui is really meant to be multiple-window interface-- detail that most of the earlier screenshots haven' really done justice to for examplefigure - shows pymailgui with the main server list windowtwo save-file list windowstwo message view windowsand help all these windows are nonmodalthat isthey are all active and independentand do not block other windows from being selectedeven though they are all running single pymailgui process in generalyou can have any number of mail view or compose windows up at onceand cut and paste between them this mattersbecause pymailgui must take care to make sure that each window has distinct text-editor object if the text-editor object were globalor used globals internallyyou' likely see the same text in each window (and the send operations might wind up sending text from another windowto avoid thispymailgui creates and attaches new texteditor instance to each view and compose window it createsand associates the new editor with the send button' callback handler to make sure we get the right text this is just the usual oop state retentionbut it acquires tangible benefit here though not gui-relatedpymailgui also prints variety of status messages as it runsbut you see them only if you launch the program from the system command-line console window ( dos box on windows or an xterm on linuxor by double-clicking on its filename icon (its main script is pynot pywon windowsyou won' see these the pymailgui client |
5,627 | messages when pymailgui is started from another programsuch as the pydemos or pygadgets launcher bar guis these status messages print server informationshow mail loading statusand trace the loadstoreand delete threads that are spawned along the way if you want pymailgui to be more verboselaunch it from command line and watchc:\pp \internet\email\pymailguipymailgui py userpp @learning-python com loading headers connecting '+ok load headers exit synch check connecting '+ok same headers text loading headers connecting '+ok load headers exit synch check connecting '+ok same headers text load connecting '+ok sending to ['lutz@rmi net''pp @learning-python com' pymailgui demo |
5,628 | content-typetext/plaincharset="us-asciicontent-transfer-encoding bit frompp @learning-python com tolutz@rmi net subjectalready got one datefri jun : : - -mailerpymailgui (pythonorigin send exit you can also double-click on the pymailgui py filename in your file explorer gui and monitor the popped-up dos console box on windows console messages are mostly intended for debuggingbut they can be used to help understand the system' operation as well for more details on using pymailguisee its help display (press the help bar at the top of its main server list windows)or read the help string in the module pymailgui help pydescribed in the next section pymailgui implementation last but not leastwe get to the code pymailgui consists of the new modules listed near the start of this along with handful of peripheral files described there the source code for these modules is listed in this section before we get startedhere are two quick reminders to help you studycode reuse besides the code herepymailgui also gets lot of mileage out of reusing modules we wrote earlier and won' repeat heremailtools for mail loadscompositionparsingand delete operationsthreadtools for managing server and local file access threadsthe gui section' texteditor for displaying and editing mail message textand so on see the example numbers list earlier in this in additionstandard python modules and packages such as poplibsmtpliband email hide most of the details of pushing bytes around the net and extracting and building message components as usualthe tkinter standard library module also implements gui components in portable fashion code structure as mentioned earlierpymailgui applies code factoring and oop to leverage code reuse for instancelist view windows are implemented as common superclass that codes most actionsalong with one subclass for the server inbox list window and one for local save-file list windows the subclasses customize the common superclass for their specific mail media this design reflects the operation of the gui itself--server list windows load mail over popand save-file list windows load from local files the basic operation of the pymailgui client |
5,629 | common superclass to avoid redundancy and simplify the code message view windows are similarly factoreda common view window superclass is reused and customized for writereplyand forward view windows to make the code easier to followit is divided into two main modules that reflect the structure of the gui--one for the implementation of list window actions and one for view window actions if you are looking for the implementation of button that appears in mail view or edit windowfor instancesee the view window module and search for method whose name begins with the word on--the convention used for callback handler methods specific button' text can also be located in name/callback tables used to build the windows actions initiated on list windows are coded in the list window module instead in additionthe message cache is split off into an object and module of its ownand potentially reusable tools are coded in importable modules ( line wrapping and utility pop upspymailgui also includes main module that defines startup window classesa simple html to plain-text parsera module that contains the help text as stringthe mailconfig user settings module ( version specific to pymailgui is used here)and small handful of related files the following subsections present each of pymailgui' source code files for you to study as you readrefer back to the demo earlier in this and run the program live to map its behavior back to its code one accounting note up-frontthe only one of pymailgui' new source files not listed in this section is its __init__ py package initialization file this file is mostly empty except for comment string and is unused in the system today it exists only for future expansionin case pymailgui is ever used as package in the future--some of its modules may be useful in other programs as isthoughsame-directory internal imports here are not package-relativeso they assume this system is either run as toplevel program (to import from "or is listed on sys path directly (to use absolute importsin python xa package' directory is not included on sys path automaticallyso future use as package would require changes to internal imports ( moving the main script up one level and using from import module throughoutsee resources such as the book learning python for more on packages and package imports pymailguithe main module example - defines the file run to start pymailgui it implements top-level list windows in the system--combinations of pymailgui' application logic and the window protocol superclasses we wrote earlier in the text the latter of these define window titlesiconsand close behavior the main internalnonuser documentation is also in this moduleas well as commandline logic--the program accepts the names of one or more save-mail files on the pymailgui implementation |
5,630 | the pydemos launcher of for example example - pp \internet\email\pymailgui\pymailgui py ""#################################################################################pymailgui python/tkinter email client client-side tkinter-based gui interface for sending and receiving email see the help string in pymailguihelp py for usage detailsand list of enhancements in this version version was majorcomplete rewrite the changes from (july ' to (jan ' were quick-access part buttons on view windowsthreaded loads and deletes of local save-mail filesand checks for and recovery from message numbers out-of-synch with mail server inbox on deletesindex loadsand message loads version ( eis port to python xuses grids instead of packed column frames for better form layout of headers in view windowsruns update(after inserting into new text editor for accurate line positioning (see pyedit loadfirst changes in )provides an html-based version of its help textextracts plain-text from html main/only parts for display and quotingsupports separators in toolbarsaddresses both message content and header unicode/ encodings for fetchedsentand saved mails (see ch and ch )and much more (see ch for the full rundown on upgrades)fetched message decoding happens deep in the mailtools packageon mail cache load operations heremailtools also fixes few email package bugs (see ch )this file implements the top-level windows and interface pymailgui uses number of modules that know nothing about this guibut perform related taskssome of which are developed in other sections of the book the mailconfig module is expanded for this program ==modules defined elsewhere and reused here:=mailtools (packageclient-side scripting server sends and receivesparsingconstruction threadtools py gui tools thread queue manangement for gui callbacks windows py gui tools border configuration for top-level windows texteditor py gui programs text widget used in mail view windowssome pop ups ==generally useful modules defined here:=popuputil py help and busy windowsfor general use messagecache py the pymailgui client (example - +(example - (example - (example - |
5,631 | wraplines py utility for wrapping long lines of messages html text py rudimentary html parser for extracting plain text mailconfig py user configuration parametersserver namesfontsetc ==program-specific modules defined here:=sharednames py objects shared between window classes and main file viewwindows py implementation of viewwritereplyforward windows listwindows py implementation of mail-server and local-file list windows pymailguihelp py (see also pymailguihelp htmluser-visible help textopened by main window bar pymailgui py maintop-level file (run this)with main window types #################################################################################""import mailconfigsys from sharednames import appnamewindows from listwindows import pymailserverpymailfile ##############################################################################top-level window classes viewwritereplyforwardhelpbusybox all inherit from popupwindow directlyonly usageaskpassword calls popupwindow and attachesthe order matters here!--pymail classes redef some method defaults in the window classeslike destroy and okaytoexitmust be leftmostto use pymailfilewindow standaloneimitate logic in pymailcommon onopenmailfile##############################################################################uses icon file in cwd or default in tools dir srvrname mailconfig popservername or 'serverclass pymailserverwindow(pymailserverwindows mainwindow)" tkwith extra protocol and mixed-in methodsdef __init__(self)windows mainwindow __init__(selfappnamesrvrnamepymailserver __init__(selfclass pymailserverpopup(pymailserverwindows popupwindow)" toplevelwith extra protocol and mixed-in methodsdef __init__(self)windows popupwindow __init__(selfappnamesrvrnanepymailserver __init__(selfclass pymailservercomponent(pymailserverwindows componentwindow)" framewith extra protocol and mixed-in methodspymailgui implementation |
5,632 | windows componentwindow __init__(selfpymailserver __init__(selfclass pymailfilewindow(pymailfilewindows popupwindow)" toplevelwith extra protocol and mixed-in methodsdef __init__(selffilename)windows popupwindow __init__(selfappnamefilenamepymailfile __init__(selffilename##############################################################################when run as top-level programcreate main mail-server list window ##############################################################################if __name__ ='__main__'rootwin pymailserverwindow(if len(sys argv for savename in sys argv[ :]rootwin onopenmailfile(savenamerootwin lift(rootwin mainloop(open server window fix to add len(open save file windows (demosave files loaded in threads sharednamesprogram-wide globals the module in example - implements sharedsystem-wide namespace that collects resources used in most modules in the system and defines global objects that span files this allows other files to avoid redundantly repeating common imports and encapsulates the locations of package importsit is the only file that must be updated if paths change in the future using globals can make programs more difficult to understand in general (the source of some names is not as clear)but it is reasonable if all such names are collected in single expected module such as this onebecause there is only one place to search for unknown names example - pp \internet\email\pymailgui\sharednames py ""#############################################################################objects shared by all window classes and main fileprogram-wide globals #############################################################################""used in all windowicon titles appname 'pymailgui used for list saveopendeletealso for sent messages file savemailseparator 'pymailgui('-'* 'pymailgui\ncurrently viewed mail save filesalso for sent-mail file opensavefiles { window per file,{name:winstandard library services import sysosemail utilsemail messagewebbrowsermimetypes the pymailgui client |
5,633 | from tkinter simpledialog import askstring from tkinter filedialog import saveasopendirectory from tkinter messagebox import showinfoshowerroraskyesno reuse book examples from pp gui tools import windows from pp gui tools import threadtools from pp internet email import mailtools from pp gui texteditor import texteditor window borderexit protocols thread callback queue checker load,send,parse,build utilities component and pop up modules defined here import mailconfig import popuputil import wraplines import messagecache import html text import pymailguihelp user paramsserversfontsetc helpbusypasswd pop-up windows wrap long message lines remember already loaded mail simplistic html->plaintext extract user documentation def printstack(exc_info)""debuggingshow exception and stack traceback on stdout change to print stack trace to real log file if print to sys stdout failsit does when launched from another program on windowswithout this workaroundpmailgui aborts and exits altogetheras this is called from the main thread on spawned thread failureslikely python bugit doesn' occur in or and the traceback object works fine if print to fileoddlythe print(calls here work (but go nowhereif spawned""print(exc_info[ ]print(exc_info[ ]import traceback trytraceback print_tb(exc_info[ ]file=sys stdoutok unless spawnedexceptlog open('_pymailerrlog txt'' 'use real file log write('-'* else gui may exit traceback print_tb(exc_info[ ]file=login xnot thread busy counters for threads run by this gui sendingbusy shared by all send windowsused by main window quit loadinghdrsbusy threadtools threadcounter(deletingbusy threadtools threadcounter(loadingmsgsbusy threadtools threadcounter(sendingbusy threadtools threadcounter(only only poss many poss many listwindowsmessage list windows the code in example - implements mail index list windows--for the server inbox window and for one or more local save-mail file windows these two types of windows look and behave largely the sameand in fact share most of their code in common in pymailgui implementation |
5,634 | load and delete calls to the server or local file list windows are created on program startup (the initial server windowand possible save-file windows for command-line options)as well as in response to open button actions in existing list windows (for opening new save-file list windowssee the open button' callback in this example for initiation code notice that the basic mail processing operations in the mailtools package from are mixed into pymailgui in variety of ways the list window classes in example - inherit from the mailtools mail parser classbut the server list window class embeds an instance of the message cache objectwhich in turn inherits from the mailtools mail fetcher the mailtools mail sender class is inherited by message view write windowsnot list windowsview windows also inherit from the mail parser this is fairly large filein principle it could be split into three filesone for each classbut these classes are so closely related that it is handy to have their code in single file for edits reallythis is one classwith two minor extensions example - pp \internet\email\pymailgui\listwindows py ""##############################################################################implementation of mail-server and save-file message list main windowsone class per kind code is factored here for reuseserver and file list windows are customized versions of the pymailcommon list window classthe server window maps actions to mail transferred from serverand the file window applies actions to local file list windows create viewwritereplyand forward windows on user actions the server list window is the main window opened on program startup by the top-level filefile list windows are opened on demand via server and file list window "openmsgnums may be temporarily out of sync with server if pop inbox changes (triggers full reload herechanges here in -now checks on deletes and loads to see if msg nums in sync with server -added up to attachment direct-access buttons on view windows -threaded save-mail file loadsto avoid -second pause for big files -also threads save-mail file deletes so file write doesn' pause gui tbd-save-mail file saves still not threadedmay pause gui brieflybut uncommon unlike load and deletesave/send only appends the local file -implementation of local save-mail files as text files with separators is mostly prototypeit loads all full mails into memoryand so limits the practical size of these filesbetter alternativeuse dbm keyed access files for hdrs and fulltextplus list to map keys to positionin this scheme save-mail files become directoriesno longer readable ##############################################################################""from sharednames import program-wide global objects the pymailgui client |
5,635 | ##############################################################################main frame general structure for both file and server message lists ##############################################################################class pymailcommon(mailtools mailparser)""an abstract widget packagewith main mail listboxmixed in with tktoplevelor frame by top-level window classesmust be customized in mode-specific subclass with actions(and othercreates view and write windows on demandthey serve as mailsenders""class attrs shared by all list windows threadloopstarted false started by first window queuecheckspersecond tweak if cpu use too high queuedelay /queuecheckspersecond min msecs between timer events queuebatch max callbacks per timer event all windows use same dialogsremember last dirs opendialog open(title=appname 'open mail file'savedialog saveas(title=appname 'append mail file' avoid downloading (fetchingsame message in parallel beingfetched set(def __init__(self)self makewidgets(if not pymailcommon threadloopstarteddraw my contentslist,tools start thread exit check loop timer event loop that dispatches queued gui callbacksjust one loop for all windowsserver,file,views can all threadself is tktoplevel,or frameany widget type will sufficeeadded queue delay/batch for progress speedup~ /secpymailcommon threadloopstarted true threadtools threadchecker(selfself queuedelayself queuebatchdef makewidgets(self)add all/none checkbtn at bottom tools frame(selfrelief=sunkenbd= cursor='hand ' configs tools pack(side=bottomfill=xself allmodevar intvar(chk checkbutton(toolstext="all"chk config(variable=self allmodevarcommand=self oncheckallchk pack(side=rightadd main buttons at bottom toolbar for (titlecallbackin self actions()if not callbacksep label(toolstext=titlesep pack(side=leftexpand=yesfill=both separator expands with window pymailgui implementation |
5,636 | button(toolstext=titlecommand=callbackpack(side=leftadd multiselect listbox with scrollbars listwide mailconfig listwidth or config start size listhigh mailconfig listheight or wide=charshigh=lines mails frame(selfvscroll scrollbar(mailshscroll scrollbar(mailsorient='horizontal'fontsz (sys platform[: ='winand or defaults listbg mailconfig listbg or 'whitelistfg mailconfig listfg or 'blacklistfont mailconfig listfont or ('courier'fontsz'normal'listbox listbox(mailsbg=listbgfg=listfgfont=listfontlistbox config(selectmode=extendedlistbox config(width=listwideheight=listhigh init wider listbox bind(''(lambda eventself onviewrawmail())crosslink listbox and scrollbars vscroll config(command=listbox yviewrelief=sunkenhscroll config(command=listbox xviewrelief=sunkenlistbox config(yscrollcommand=vscroll setrelief=sunkenlistbox config(xscrollcommand=hscroll setpack last clip first mails pack(side=topexpand=yesfill=bothvscroll pack(side=rightfill=bothhscroll pack(side=bottomfill=bothlistbox pack(side=leftexpand=yesfill=bothself listbox listbox ################event handlers ################def oncheckall(self)all or none click if self allmodevar get()self listbox select_set( endelseself listbox select_clear( enddef onviewrawmail(self)possibly threadedview selected messages raw text headersbody msgnums self verifyselectedmsgs(if msgnumsself getmessages(msgnumsafter=lambdaself contviewraw(msgnums)def contviewraw(selfmsgnumspyedit=true)do we need full texteditorfor msgnum in msgnumscould be nested def fulltext self getmessage(msgnumfulltext is unicode decoded if not pyeditdisplay in scrolledtext from tkinter scrolledtext import scrolledtext window windows quietpopupwindow(appname'raw message viewer' the pymailgui client |
5,637 | browser insert(' 'fulltextbrowser pack(expand=yesfill=bothelseemore useful pyedit text editor wintitle raw message textbrowser texteditor texteditormainpopup(selfwintitle=wintitlebrowser update(browser setalltext(fulltextbrowser clearmodified(def onviewformatmail(self)""possibly threadedview selected messages pop up formatted display not threaded if in savefile listor messages are already loaded the after action runs only if getmessages prefetch allowed and worked ""msgnums self verifyselectedmsgs(if msgnumsself getmessages(msgnumsafter=lambdaself contviewfmt(msgnums)def contviewfmt(selfmsgnums)""finish viewextract main textpopup view window(sto displayextracts plain text from html text if requiredwraps text lineshtml mailsshow extracted textthen save in temp file and open in web browserpart can also be opened manually from view window split or part buttonif non-multipartotherpart must be opened manually with split or part buttonverify html open per mailconfig for html-only mailsmain text is str herebut save its raw bytes in binary mode to finesse encodingsworth the effort because many mails are just html todaythis first tried encoding guesses (utf- latin- platform dflt)but now gets and saves raw bytes to minimize any fidelity lossif part is later opened on demandit is saved in binary file as raw bytes in the same waycaveatthe spawned web browser won' have any original email headersit may still have to guess or be told the encodingunless the html already has its own encoding headers (these take the form of html tags within sections if presentnone are inserted in the html hereas some well-formed html parts have them)ie seems to handle most html part files anyhowalways encoding html parts to utf- may suffice toothis encoding can handle most types of text""for msgnum in msgnumsfulltext self getmessage(msgnum str for parser message self parsemessage(fulltexttypecontent self findmaintext(message unicode decoded if type in ['text/html''text/xml'] get plain text content html text html text(contentcontent wraplines wraptext (contentmailconfig wrapszviewwindow(headermap messageshowtext contentorigmessage message decodes headers pymailgui implementation |
5,638 | if type ='text/html'if ((not mailconfig verifyhtmltextopenor askyesno(appname'open message text in browser?')) get post mime decodepre unicode decode bytes typeasbytes self findmaintext(messageasstr=falsetryfrom tempfile import gettempdir or tk html viewertempname os path join(gettempdir()'pymailgui html'tmp open(tempname'wb'already encoded tmp write(asbyteswebbrowser open_new('file://tempnameexceptshowerror(appname'cannot open in browser'def onwritemail(self)""compose new email from scratchwithout fetching othersnothing to quote herebut adds sigand prefills bcc with the sender' address if this optional header enabled in mailconfigfrom may be encoded in mailconfigview window will decode""starttext '\nuse auto signature text if mailconfig mysignaturestarttext +'% \nmailconfig mysignature from mailconfig myaddress writewindow(starttext starttextheadermap dict(from=frombcc=from) prefill bcc def onreplymail(self)possibly threadedreply to selected emails msgnums self verifyselectedmsgs(if msgnumsself getmessages(msgnumsafter=lambdaself contreply(msgnums)def contreply(selfmsgnums)""finish replydrop attachmentsquote with '>'add signaturepresets initial to/from values from mail or config moduledon' use original to for frommay be many or listnameto keeps nameformat even if ',separator in nameuses original from for toignores reply-to header is any replies also copy to all original recipients by default now uses getaddresses/parseaddr full parsing to separate addrs on commasand handle any commas that appear nested in email name partsmultiple addresses are separated by comma in guiwe copy comma separators when displaying headersand we use getaddresses to split addrs as needed',is required by servers for separatorno longer uses parseaddr to get st name/addr pair of getaddresses resultuse full from for to we decode the subject header here because we need its text the pymailgui client |
5,639 | on all displayed headers (the extra subject decode is no-op)on sendsall non-ascii hdrs and hdr email names are in decoded form in the guibut are encoded within the mailtools packagequoteorigtext also decodes the initial headers it inserts into the quoted text blockand index lists decode for display""for msgnum in msgnumsfulltext self getmessage(msgnummessage self parsemessage(fulltextmay failerror obj maintext self formatquotedmaintext(messagesame as forward from and to are decoded by view window from mailconfig myaddress not original to to message get('from''' ',sept cc self replycopyto(message cc all recipientssubj message get('subject''(no subject)'subj self decodeheader(subjdeocde for str if subj[: lower(!'re' unify case subj 'resubj replywindow(starttext maintextheadermap dict(from=fromto=tocc=ccsubject=subjbcc=from)def onfwdmail(self)possibly threadedforward selected emails msgnums self verifyselectedmsgs(if msgnumsself getmessages(msgnumsafter=lambdaself contfwd(msgnums)def contfwd(selfmsgnums)""finish forwarddrop attachmentsquote with '>'add signaturesee notes about headers decoding in the reply action methodsview window superclass will decode the from header we pass here""for msgnum in msgnumsfulltext self getmessage(msgnummessage self parsemessage(fulltextmaintext self formatquotedmaintext(messagesame as reply initial from value from confignot mail from mailconfig myaddress encoded or not subj message get('subject''(no subject)'subj self decodeheader(subj send encodes if subj[: lower(!'fwd' unify case subj 'fwdsubj forwardwindow(starttext maintextheadermap dict(from=fromsubject=subjbcc=from)def onsavemailfile(self)""save selected emails to file for offline viewingdisabled if target file load/delete is in progressdisabled by getmessages if self is busy file toopymailgui implementation |
5,640 | ""msgnums self selectedmsgs(if not msgnumsshowerror(appname'no message selected'elsecaveatdialog warns about replacing file filename self savedialog show(shared class attr if filenamedon' verify num msgs filename os path abspath(filenamenormalize to self getmessages(msgnumsafter=lambdaself contsave(msgnumsfilename)def contsave(selfmsgnumsfilename)test busy nowafter poss srvr msgs load if (filename in opensavefiles keys(and viewing this fileopensavefiles[filenameopenfilebusy)load/del occurringshowerror(appname'target file busy cannot save'elsetrycaveat:not threaded fulltextlist [ use encoding mailfile open(filename' 'encoding=mailconfig fetchencodingfor msgnum in msgnums sec for megs fulltext self getmessage(msgnumbut poss many msgs if fulltext[- !'\ 'fulltext +'\nmailfile write(savemailseparatormailfile write(fulltextfulltextlist append(fulltextmailfile close(exceptshowerror(appname'error during save'printstack(sys exc_info()elsewhy keys()eibti if filename in opensavefiles keys()viewing this filewindow opensavefiles[filenameupdate listraise window addsavedmails(fulltextlistavoid file reload #window loadmailfilethread(this was very slow def onopenmailfile(selffilename=none)process saved mail offline filename filename or self opendialog show(if filenamefilename os path abspath(filenameif filename in opensavefiles keys()opensavefiles[filenamelift(showinfo(appname'file already open'elsefrom pymailgui import pymailfilewindow popup pymailfilewindow(filenameopensavefiles[filenamepopup popup loadmailfilethread(def ondeletemail(self)delete selected mails from server or file msgnums self selectedmsgs( the pymailgui client shared class attr match on full name only win per file raise file' window else deletes odd avoid duplicate win new list window removed in quit try load in thread subclassfillindex |
5,641 | always verify here showerror(appname'no message selected'elseif askyesno(appname'verify delete % mails?len(msgnums))self dodelete(msgnums#################utility methods #################def selectedmsgs(self)get messages selected in main listbox selections self listbox curselection(return [int( )+ for in selectionstuple of digit strs - convert to intsmake warninglimit def verifyselectedmsgs(self)msgnums self selectedmsgs(if not msgnumsshowerror(appname'no message selected'elsenumselects len(msgnumsif numselects self warninglimitif not askyesno(appname'open % selections?numselects)msgnums [return msgnums def fillindex(selfmaxhdrsize= )""fill all of main listbox from message header mappings decode headers per email/mime/unicode here if encoded caveatlarge chinese characters can break '|alignment""hdrmaps self headersmaps(may be empty showhdrs ('subject''from''date''to'default hdrs to show if hasattr(mailconfig'listheaders')mailconfig customizes showhdrs mailconfig listheaders or showhdrs addrhdrs ('from''to''cc''bcc' decode specially compute max field sizes <hdrsize maxsize {for key in showhdrsalllens [too big for list compfor msg in hdrmapskeyval msg get(key'if key not in addrhdrsalllens append(len(self decodeheader(keyval))elsealllens append(len(self decodeaddrheader(keyval))if not alllensalllens [ maxsize[keymin(maxhdrsizemax(alllens)populate listbox with fixed-width left-justified fields self listbox delete( endshow multiparts with for (ixmsgin enumerate(hdrmaps)via content-type hdr pymailgui implementation |
5,642 | no is_multipart yet msgline (msgtype ='multipartand '*'or msgline +'% (ix+ for key in showhdrsmysize maxsize[keyif key not in addrhdrskeytext self decodeheader(msg get(key')elsekeytext self decodeaddrheader(msg get(key')msgline +%-* (mysizekeytext[:mysize]msgline +' fk(self mailsize(ix+ optional self listbox insert(endmsglineself listbox see(endshow most recent mail=last line def replycopyto(selfmessage)"" replies copy all original recipientsby prefilling cc header with all addreses in original to and cc after removing duplicates and new sendercould decode addrs herebut the view window will decode to display (and send will reencodeand the unique set filtering here will work either waythough sender' address is assumed to be in encoded form in mailconfig (else it is not removed here)empty to or cc headers are okaysplit returns empty lists""if not mailconfig repliescopytoallreply to sender only cc 'elsecopy all original recipients ( allrecipients (self splitaddresses(message get('to''')self splitaddresses(message get('cc'''))uniqueothers set(allrecipientsset([mailconfig myaddress]cc 'join(uniqueothersreturn cc or '?def formatquotedmaintext(selfmessage)"" factor out common code shared by reply and forwardfetch decoded textextract text if htmlline wrapadd quote ""typemaintext self findmaintext(message decoded str if type in ['text/html''text/xml'] get plain text maintext html text html text(maintextmaintext wraplines wraptext (maintextmailconfig wrapsz- 'maintext self quoteorigtext(maintextmessageadd hdrsif mailconfig mysignaturemaintext ('\ % \nmailconfig mysignaturemaintext return maintext def quoteorigtext(selfmaintextmessage)"" we need to decode any (internationalizdheaders here tooor they show up in email+mime encoded form in the quoted text blockdecodeaddrheader works on one addr or all in comma-separated list the pymailgui client |
5,643 | also already in fully decoded formcould be in any unicode scheme""quoted '\noriginal message\nfor hdr in ('from''to''subject''date')rawhdr message get(hdr'?'if hdr not in ('from''to')dechdr self decodeheader(rawhdrfull value elsedechdr self decodeaddrheader(rawhdrname parts only quoted +'% % \ (hdrdechdrquoted +'\nmaintext quoted '\nquoted replace('\ ''\ 'return quoted #######################subclass requirements #######################def getmessages(selfmsgnumsafter)after(used by view,save,reply,fwd redef if cachethread test plus okaytoquit?any unique actions def getmessage(selfmsgnum)assert false def headersmaps(self)assert false def mailsize(selfmsgnum)assert false def dodelete(self)assert false used by manyfull mail text fillindexhdr mappings list fillindexsize of msgnum ondeletemaildelete button ##############################################################################main window when viewing messages in local save file (or sent-mail file##############################################################################class pymailfile(pymailcommon)""customize pymailcommon for viewing saved-mail file offlinemixed with tktoplevelor frameadds main mail listboxmaps loadfetchdelete actions to local text file storagefile opens and deletes here run in threads for large filessave and send not threadedbecause only append to filesave is disabled if source or target file busy with load/deletesave disables loaddeletesave just because it is not run in thread (blocks gui)tbdmay need thread and / file locks if saves ever do run in threadssaves could disable other threads with openfilebusybut file may not be open in guifile locks not sufficientbecause gui updated tootbdappends to sent-mail file may require / locksas isuser gets error pop up if sent during load/del mail save files are now unicode textencoded per an encoding name setting in the mailconfig modulethis may not support worst case scenarios of unusual or mixed encodingsbut most full mail pymailgui implementation |
5,644 | ""def actions(self)return ('open'self onopenmailfile)('write'self onwritemail)('none) separators ('view'self onviewformatmail)('reply'self onreplymail)('fwd'self onfwdmail)('save'self onsavemailfile)('delete'self ondeletemail)('none)('quit'self quitdef __init__(selffilename)callerdo loadmailfilethread next pymailcommon __init__(selfself filename filename self openfilebusy threadtools threadcounter(one per window def loadmailfilethread(self)""load or reload file and update window index listcalled on openstartupand possibly on send if sent-mail file appended is currently openthere is always bogus first item after the text splitalt[self parseheaders(mfor in self msglist]could pop up busy dialogbut quick for small files this is now threaded--else runs sec for meg filesbut can pause gui seconds if very large filesave now uses addsavedmails to append msg lists for speednot this reloadstill called from send just because msg text unavailable requires refactoringdelete threaded tooprevent open and delete overlap""if self openfilebusydon' allow parallel open/delete changes errmsg 'cannot loadfile is busy:\ "% "self filename showerror(appnameerrmsgelse#self listbox insert(end'loading 'error if user clicks savetitle self title(set by window class self title(appname 'loading 'self openfilebusy incr(threadtools startthreadaction self loadmailfileargs ()context (savetitle,)onexit self onloadmailfileexitonfail self onloadmailfilefaildef loadmailfile(self)run in thread while gui is active openreadparser may all raise excscaught in thread utility the pymailgui client |
5,645 | allmsgs file read(self msglist allmsgs split(savemailseparator)[ :full text self hdrlist list(map(self parseheadersself msglist)msg objects def onloadmailfileexit(selfsavetitle)on thread success self title(savetitlereset window title to filename self fillindex(updates guido in main thread self lift(raise my window self openfilebusy decr(def onloadmailfilefail(selfexc_infosavetitle)on thread exception showerror(appname'error opening "% "\ % \ % ((self filename,exc_info[: ])printstack(exc_infoself destroy(always close my windowself openfilebusy decr(not needed if destroy def addsavedmails(selffulltextlist)""optimizationextend loaded file lists for mails newly saved to this window' filein past called loadmailthread to reload entire file on save slowmust be called in main gui thread onlyupdates guisends still reloads sent file if openno msg text""self msglist extend(fulltextlistself hdrlist extend(map(self parseheadersfulltextlist) iter ok self fillindex(self lift(def dodelete(selfmsgnums)""simple-mindedbut sufficientrewrite all nondeleted mails to filecan' just delete from self msglist in-placechanges item indexespy enumerate(lsame as zip(range(len( )) now threadedelse sec pause for large files ""if self openfilebusydont allow parallel open/delete changes errmsg 'cannot deletefile is busy:\ "% "self filename showerror(appnameerrmsgelsesavetitle self title(self title(appname 'deleting 'self openfilebusy incr(threadtools startthreadaction self deletemailfileargs (msgnums,)context (savetitle,)onexit self ondeletemailfileexitonfail self ondeletemailfilefailpymailgui implementation |
5,646 | run in thread while gui active indexed enumerate(self msglistkeepers [msg for (ixmsgin indexed if ix+ not in msgnumsallmsgs savemailseparator join([''keepersfile open(self filename' 'encoding=mailconfig fetchencodingfile write(allmsgsself msglist keepers self hdrlist list(map(self parseheadersself msglist)def ondeletemailfileexit(selfsavetitle)self title(savetitleself fillindex(updates guido in main thread self lift(reset my titleraise my window self openfilebusy decr(def ondeletemailfilefail(selfexc_infosavetitle)showerror(appname'error deleting "% "\ % \ % ((self filename,exc_info[: ])printstack(exc_infoself destroy(always close my windowself openfilebusy decr(not needed if destroy def getmessages(selfmsgnumsafter)""used by view,save,reply,fwdfile load and delete threads may change the msg and hdr listsso disable all other operations that depend on them to be safethis test is for selfsaves also test target file""if self openfilebusyerrmsg 'cannot fetchfile is busy:\ "% "self filename showerror(appnameerrmsgelseafter(mail already loaded def getmessage(selfmsgnum)return self msglist[msgnum- full text of mail def headersmaps(self)return self hdrlist email message message objects def mailsize(selfmsgnum)return len(self msglist[msgnum- ]def quit(self)don' destroy during updatefillindex next if self openfilebusyshowerror(appname'cannot quit during load or delete'elseif askyesno(appname'verify quit window?')delete file from open list del opensavefiles[self filenametoplevel destroy(self the pymailgui client |
5,647 | main window when viewing messages on the mail server ##############################################################################class pymailserver(pymailcommon)""customize pymailcommon for viewing mail still on servermixed with tktoplevelor frameadds main mail listboxmaps loadfetchdelete actions to email server inboxembeds messagecachewhich is mailtools mailfetcher""def actions(self)return ('load'self onloadserver)('open'self onopenmailfile)('write'self onwritemail)('none) separators ('view'self onviewformatmail)('reply'self onreplymail)('fwd'self onfwdmail)('save'self onsavemailfile)('delete'self ondeletemail)('none)('quit'self quitdef __init__(self)pymailcommon __init__(selfself cache messagecache guimessagecache(embeddednot inherited #self listbox insert(end'press load to fetch mail'def makewidgets(self)self addhelpbar(pymailcommon makewidgets(selfhelp barmain win only def addhelpbar(self)msg 'pymailgui python/tkinter email client (help)title button(selftext=msgtitle config(bg='steelblue'fg='white'relief=ridgetitle config(command=self onshowhelptitle pack(fill=xdef onshowhelp(self)""load,show text block string now uses html and webbrowser module here too user setting in mailconfig selects texthtmlor both always displays one or the otherhtml if both false ""if mailconfig showhelpastextfrom pymailguihelp import helptext popuputil helppopup(appnamehelptextshowsource=self onshowmysourceif mailconfig showhelpashtml or (not mailconfig showhelpastext)pymailgui implementation |
5,648 | showhtmlhelp( html version without source file links def onshowmysource(selfshowasmail=false)""display my sourcecode fileplus imported modules here elsewhere ""import pymailguilistwindowsviewwindowssharednamestextconfig from pp internet email mailtools import mailtools now pkg mailsendermailfetchermailparsercan' use in def mymods pymailguilistwindowsviewwindowssharednamespymailguihelppopuputilmessagecachewraplineshtml textmailtoolsmailfetchermailsendermailparsermailconfigtextconfigthreadtoolswindowstexteditorfor mod in mymodssource mod __file__ if source endswith(pyc')source source[:- pyassume py in same dir if showasmailthis is bit cheesey code open(sourceread( platform encoding user mailconfig myaddress hdrmap {'from'appname'to'user'subject'mod __name__viewwindow(showtext=codeheadermap=hdrmaporigmessage=email message message()elsemore useful pyedit text editor eassume in utf unicode encoding (else peedit may ask!wintitle mod __name__ texteditor texteditormainpopup(selfsourcewintitle'utf- 'def onloadserver(selfforcereload=false)""threadedload or reload mail headers list on requestexit,fail,progress run by threadchecker after callback via queueload may overlap with sendsbut disables all but sendcould overlap with loadingmsgsbut may change msg cache listforcereload on delete/synch failelse loads recent arrivals only cache loadheaders may do quick check to see if msgnums in synch with serverif we are loading just newly arrived hdrs""if loadinghdrsbusy or deletingbusy or loadingmsgsbusyshowerror(appname'cannot load headers during load or delete'elseloadinghdrsbusy incr(self cache setpoppassword(appnamedon' update gui in the threadpopup popuputil busyboxnowait(appname'loading message headers'threadtools startthreadaction self cache loadheadersargs (forcereload,)context (popup,)onexit self onloadhdrsexitonfail self onloadhdrsfail the pymailgui client |
5,649 | def onloadhdrsexit(selfpopup)self fillindex(popup quit(self lift(loadinghdrsbusy decr(allow other actions to run def onloadhdrsfail(selfexc_infopopup)popup quit(showerror(appname'load failed\ % \ %sexc_info[: ]printstack(exc_infosend stack trace to stdout loadinghdrsbusy decr(if exc_info[ =mailtools messagesyncherrorsynch inbox/index self onloadserver(forcereload=truenew threadreload elseself cache poppassword none force re-input next time def onloadhdrsprogress(selfinpopup)popup changetext('% of % (in)def dodelete(selfmsgnumlist)""threadeddelete from server now changes msg numsmay overlap with sends onlydisables all except sends cache deletemessages now checks top result to see if headers match selected mailsin case msgnums out of synch with mail serverposs if mail deleted by other clientor server deletes inbox mail automatically some isps may move mail from inbox to undeliverable on load failure""if loadinghdrsbusy or deletingbusy or loadingmsgsbusyshowerror(appname'cannot delete during load or delete'elsedeletingbusy incr(popup popuputil busyboxnowait(appname'deleting selected mails'threadtools startthreadaction self cache deletemessagesargs (msgnumlist,)context (popup,)onexit self ondeleteexitonfail self ondeletefailonprogress self ondeleteprogressdef ondeleteexit(selfpopup)self fillindex(popup quit(self lift(deletingbusy decr(no need to reload from server refill index with updated cache raise index windowrelease lock def ondeletefail(selfexc_infopopup)popup quit(showerror(appname'delete failed\ % \ %sexc_info[: ]printstack(exc_infodeletingbusy decr(delete or synch check failure pymailgui implementation |
5,650 | new threadsome msgnums changed def ondeleteprogress(selfinpopup)popup changetext('% of % (in)def getmessages(selfmsgnumsafter)""threadedprefetch all selected messages into cache nowused by saveviewreplyand forward to prefill cachemay overlap with other loadmsgs and sendsdisables delete,loadonly runs "afteraction if the fetch allowed and successful cache getmessages tests if index in synch with serverbut we only test if we have to go to servernot if cached see messagecache notenow avoids potential fetch of mail currently being fetchedif user clicks again while in progressany message being fetched by any other request in progress must disable entire toload batchelseneed to wait for other loadsfetches are still allowed to overlap in timeas long as disjoint""if loadinghdrsbusy or deletingbusyshowerror(appname'cannot fetch message during load or delete'elsetoload [num for num in msgnums if not self cache isloaded(num)if not toloadafter(all already loaded return process nowno wait pop up elseif set(toloadself beingfetched any in progressshowerror(appname'cannot fetch any message being fetched'elseself beingfetched |set(toloadloadingmsgsbusy incr(from popuputil import busyboxnowait popup busyboxnowait(appname'fetching message contents'threadtools startthreadaction self cache getmessagesargs (toload,)context (afterpopuptoload)onexit self onloadmsgsexitonfail self onloadmsgsfailonprogress self onloadmsgsprogressdef onloadmsgsexit(selfafterpopuptoload)self beingfetched -set(toloadpopup quit(after(loadingmsgsbusy decr(allow other actions after onexit done def onloadmsgsfail(selfexc_infoafterpopuptoload)self beingfetched -set(toloadpopup quit(showerror(appname'fetch failed\ % \ %sexc_info[: ]printstack(exc_infoloadingmsgsbusy decr( the pymailgui client |
5,651 | self onloadserver(forcereload=truesynch inbox/index new threadreload def onloadmsgsprogress(selfinafterpopuptoload)popup changetext('% of % (in)def getmessage(selfmsgnum)return self cache getmessage(msgnumfull mail text def headersmaps(self)list of email message message objects requires list(if map(return [self parseheaders(hfor in self cache allhdrs()return list(map(self parseheadersself cache allhdrs())def mailsize(selfmsgnum)return self cache getsize(msgnumdef okaytoquit(self)any threads still runningfilesbusy [win for win in opensavefiles values(if win openfilebusybusy loadinghdrsbusy or deletingbusy or sendingbusy or loadingmsgsbusy busy busy or filesbusy return not busy viewwindowsmessage view windows example - lists the implementation of mail view and edit windows these windows are created in response to actions in list windows--viewwritereplyand forward buttons see the callbacks for these actions in the list window module of example - for view window initiation calls as in the prior module (example - )this file is really one common class and handful of customizations the mail view window is nearly identical to the mail edit windowused for writereplyand forward requests consequentlythis example defines the common appearance and behavior in the view window superclassand extends it by subclassing for edit windows replies and forwards are hardly different from the write window herebecause their details ( from and to addresses and quoted message textare worked out in the list window implementation before an edit window is created example - pp \internet\email\pymailgui\viewwindows py ""##############################################################################implementation of viewwritereplyforward windowsone class per kind code is factored here for reusea write window is customized view windowand reply and forward are custom write windows windows defined in this file are created by the list windowsin response to user actions caveat:'splitpop ups for opening parts/attachments feel nonintuitive this caveat was addressedby adding quick-access attachment buttons new in platform-neutral grid(for mail headersnot packed col frames pymailgui implementation |
5,652 | new in pyedit supports arbitrary unicode for message parts viewed new in supports unicode/mail encodings for headers in mails sent tbdcould avoid verifying quits unless text area modified (like pyedit )but these windows are largerand would not catch headers already changed tbdshould open dialog in write windows be program-wide(per-window now##############################################################################""from sharednames import program-wide global objects ##############################################################################message view window also superclass of writereplyforward ##############################################################################class viewwindow(windows popupwindowmailtools mailparser)"" toplevelwith extra protocol and embedded texteditorinherits saveparts,partslist from mailtools mailparsermixes in custom subclass logic by direct inheritance here""class attributes modelabel 'viewused in window titles from mailconfig import okaytoopenparts open any attachments at allfrom mailconfig import verifypartopens ask before open each partfrom mailconfig import maxpartbuttons show up to this many from mailconfig import skiptextonhtmlpart just browsernot pyedittemppartdir 'temppartswhere selected part saved all view windows use same dialogremembers last dir partsdialog directory(title=appname 'select parts save directory'def __init__(selfheadermapshowtextorigmessage=none)""header map is origmessageor custom hdr dict for writingshowtext is main text part of the messageparsed or customorigmessage is parsed email message message for view mail windows ""windows popupwindow __init__(selfappnameself modelabelself origmessage origmessage self makewidgets(headermapshowtextdef makewidgets(selfheadermapshowtext)""add headersactionsattachmentstext editor showtext is assumed to be decoded unicode str hereit will be encoded on sends and saves as directed/needed""actionsframe self makeheaders(headermapif self origmessage and self okaytoopenpartsself makepartbuttons(self editor texteditor texteditorcomponentminimal(self the pymailgui client |
5,653 | self actionbuttons(for (labelcallbackin myactionsb button(actionsframetext=labelcommand=callbackb config(bg='beige'relief=ridgebd= pack(side=topexpand=yesfill=bothbody textpack last=clip first self editor pack(side=bottommay be multiple editors self update( else may be line self editor setalltext(showtexteach has own content lines len(showtext splitlines()lines min(lines mailconfig viewheight or self editor setheight(lineselse height= width= self editor setwidth( or from pyedit textconfig if mailconfig viewbgself editor setbg(mailconfig viewbgcolorsfont in mailconfig if mailconfig viewfgself editor setfg(mailconfig viewfgif mailconfig viewfontalso via editor tools menu self editor setfont(mailconfig viewfontdef makeheaders(selfheadermap)""add header entry fieldsreturn action buttons frame uses grid for platform-neutral layout of label/entry rowspacked row frames with fixed-width labels would work well too decoding of headers (and email names in address headersis performed here if still required as they are added to the guisome may have been decoded already for reply/forward windows that need to use decoded textbut the extra decode here is harmless for theseand is required for other headers and cases such as fetched mail viewsalwaysheaders are in decoded form when displayed in the guiand will be encoded within mailtools on sends if they are non-ascii (see write) header decoding also occurs in list window mail indexesand for headers added to quoted mail texttext payloads in the mail body are also decoded for display and encoded for sends elsewhere in the system (list windowswrite) creators of edit windows prefill bcc header with sender email address to be picked up hereas convenience for common usages if this header is enabled in mailconfigreply also now prefills the cc header with all unique original recipients less fromif enabled""top frame(self)top pack (side=topfill=xleft frame(top)left pack (side=leftexpand=nofill=bothmiddle frame(top)middle pack(side=leftexpand=yesfill=xheaders set may be extended in mailconfig (bccothers?self userhdrs (showhdrs ('from''to''cc''subject'if hasattr(mailconfig'viewheaders'and mailconfig viewheadersself userhdrs mailconfig viewheaders showhdrs +self userhdrs addrhdrs ('from''to''cc''bcc' decode specially pymailgui implementation |
5,654 | for (iheaderin enumerate(showhdrs)lab label(middletext=header+':'justify=leftent entry(middlelab grid(row=icolumn= sticky=ewent grid(row=icolumn= sticky=ewmiddle rowconfigure(iweight= hdrvalue headermap get(header'?'might be empty if encodeddecode per email+mime+unicode if header not in addrhdrshdrvalue self decodeheader(hdrvalueelsehdrvalue self decodeaddrheader(hdrvalueent insert(' 'hdrvalueself hdrfields append(entorder matters in onsend middle columnconfigure( weight= return left def actionbuttons(self)return [('cancel'self destroy)('parts'self onparts)('split'self onsplit)must be method for self close view window silently multiparts list or the body def makepartbuttons(self)""add up to buttons that open attachments/parts when clickedalternative to parts/split ( )okay that temp dir is shared by all open messagespart file not saved till later selected and openedpartname=partname is required in lambda in py caveatwe could try to skip the main text part""def makebutton(parenttextcallback)link button(parenttext=textcommand=callbackrelief=sunkenif mailconfig partfglink config(fg=mailconfig partfgif mailconfig partbglink config(bg=mailconfig partbglink pack(side=leftfill=xexpand=yesparts frame(selfparts pack(side=topexpand=nofill=xfor (countpartnamein enumerate(self partslist(self origmessage))if count =self maxpartbuttonsmakebutton(parts'self onsplitbreak openpart (lambda partname=partnameself ononepart(partname)makebutton(partspartnameopenpartdef ononepart(selfpartname)""locate selected part for button and save and openokay if multiple mails openresaves each time selectedwe could probably just use web browser directly herecaveattemppartdir is relative to cwd poss anywherecaveattemppartdir is never cleaned upmight be large the pymailgui client |
5,655 | part display code in onview of the list window class)""trysavedir self temppartdir message self origmessage (contypesavepathself saveonepart(savedirpartnamemessageexceptshowerror(appname'error while writing part file'printstack(sys exc_info()elseself openparts([(contypeos path abspath(savepath))]reuse def onparts(self)""show message part/attachments in pop-up windowuses same file naming scheme as save on splitif non-multipartsingle part full body text ""partnames self partslist(self origmessagemsg '\njoin(['message parts:\ 'partnamesshowinfo(appnamemsgdef onsplit(self)""pop up save dir dialog and save all parts/attachments thereif desiredpop up html and multimedia parts in web browsertext in texteditorand well-known doc types on windowscould show parts in view windows where embedded text editor would provide save buttonbut most are not readable text""savedir self partsdialog show(class attrat prior dir if savedirtk dir choosernot file trypartfiles self saveparts(savedirself origmessageexceptshowerror(appname'error while writing part files'printstack(sys exc_info()elseif self okaytoopenpartsself openparts(partfilesdef askopen(selfappnameprompt)if not self verifypartopensreturn true elsereturn askyesno(appnamepromptpop-up dialog def openparts(selfpartfiles)""auto-open well known and safe file typesbut only if verified by the user in pop upother types must be opened manually from save dirat this pointthe named parts have been already mime-decoded and saved as raw bytes in binary-mode filesbut text parts may be in any unicode encodingpyedit needs to know the encoding to decodewebbrowsers may have to guess or be toldpymailgui implementation |
5,656 | safe filename extension such as htmlcaveatimage/audio/video could be opened with the book' playfile pycould also do that if text viewer failswould start notepad on windows via startfilewebbrowser may handle most cases here toobut specific is better""def textpartencoding(fullfilename)"" map text part filename back to charset param in content-type header of part' messageso we can pass this on to the pyedit constructor for proper text displaywe could return the charset along with content-type from mailtools for text partsbut fewer changes are needed if this is handled as special case herepart content is saved in binary mode files by mailtools to avoid encoding issuesbut here the original part message is not directly availablewe need this mapping step to extract unicode encoding name if present ' pyedit now allows an explicit encoding name for file opensand resolves encoding on savessee for pyedit policiesit may ask user for an encoding if charset absent or failscaveatmove to mailtools mailparser to reuse for in pymailcgi""partname os path basename(fullfilenamefor (filenamecontypepartin self walknamedparts(self origmessage)if filename =partnamereturn part get_content_charset(none if not in header assert false'text part not foundshould never happen for (contypefullfilenamein partfilesmaintype contype split('/')[ extension os path splitext(fullfilename)[ basename os path basename(fullfilenameleft side not [- :strip dir html and xml textweb pagessome media if contype in ['text/html''text/xml']browseropened false if self askopen(appname'open "%sin browser?basename)trywebbrowser open_new('file://fullfilenamebrowseropened true exceptshowerror(appname'browser failedtrying editor'if not browseropened or not self skiptextonhtmlparttrytry pyedit to see encoding name and effect encoding textpartencoding(fullfilenametexteditor texteditormainpopup(parent=selfwintitle=% email part(encoding or '?')loadfirst=fullfilenameloadencode=encodingexceptshowerror(appname'error opening text viewer'text/plaintext/ -pythonetc eencodingmay fail the pymailgui client |
5,657 | if self askopen(appname'open text part "% "?basename)tryencoding textpartencoding(fullfilenametexteditor texteditormainpopup(parent=selfwintitle=% email part(encoding or '?')loadfirst=fullfilenameloadencode=encodingexceptshowerror(appname'error opening text viewer'multimedia typeswindows opens mediaplayerimagevieweretc elif maintype in ['image''audio''video']if self askopen(appname'open media part "% "?basename)trywebbrowser open_new('file://fullfilenameexceptshowerror(appname'error opening browser'common windows documentswordexceladobearchivesetc elif (sys platform[: ='winand maintype ='applicationand + types extension in [doc'docx'xls'xlsx'generalize me pdf'zip'tar'wmv'])if self askopen(appname'open part "% "?basename)os startfile(fullfilenameelsepuntmsg 'cannot open part"% "\nopen manually in"% "msg msg (basenameos path dirname(fullfilename)showinfo(appnamemsg##############################################################################message edit windows writereplyforward ##############################################################################if mailconfig smtpusermailsenderclass mailtools mailsenderauth elsemailsenderclass mailtools mailsender user set in mailconfiglogin/password required class writewindow(viewwindowmailsenderclass)""customize view display for composing new mail inherits sendmessage from mailtools mailsender ""modelabel 'writedef __init__(selfheadermapstarttext)viewwindow __init__(selfheadermapstarttextmailsenderclass __init__(selfself attaches [each win has own open dialog self opendialog none dialog remembers last dir pymailgui implementation |
5,658 | return [('cancel'self quit)('parts'self onparts)('attach'self onattach)('send'self onsend)need method to use self popupwindow verifies cancel edon' padcentered def onparts(self)caveatdeletes not currently supported if not self attachesshowinfo(appname'nothing attached'elsemsg '\njoin(['already attached:\ 'self attachesshowinfo(appnamemsgdef onattach(self)""attach file to the mailname added here will be added as part on sendinside the mailtools pkg ecould ask unicode type here instead of on send ""if not self opendialogself opendialog open(title=appname 'select attachment file'filename self opendialog show(remember prior dir if filenameself attaches append(filenameto be opened in send method def resolveunicodeencodings(self)""eto prepare for sendresolve unicode encoding for text partsboth main text partand any text part attachmentsthe main text part may have had known encoding if this is reply or forwardbut not for writeand it may require different encoding after editing anyhowsmtplib in requires that full message text be encodable per ascii when sent (if it' str)so it' crucial to get this right hereelse fails if reply/fwd to utf text when config=ascii if any non-ascii charstry user setting and reply but fall back on general utf as last resort""def istextkind(filename)contypeencoding mimetypes guess_type(filenameif contype is none or encoding is not none utility return false no guesscompressedmaintypesubtype contype split('/' check for text/return maintype ='textresolve many body text encoding bodytextencoding mailconfig maintextencoding if bodytextencoding =noneasknow askstring('pymailgui''enter main text unicode encoding name'bodytextencoding asknow or 'latin- or sys getdefaultencoding()last chanceuse utf- if can' encode per prior selections if bodytextencoding !'utf- 'try the pymailgui client |
5,659 | bodytext encode(bodytextencodingexcept (unicodeerrorlookuperror)bodytextencoding 'utf- lookupbad encoding name general code point scheme resolve any text part attachment encodings attachesencodings [config mailconfig attachmenttextencoding for filename in self attachesif not istextkind(filename)attachesencodings append(noneskip non-textdon' ask elif config !noneattachesencodings append(configfor all text parts if set elseprompt 'enter unicode encoding name for %filename asknow askstring('pymailgui'promptattachesencodings append(asknow or 'latin- 'last chanceuse utf- if can' decode per prior selections choice attachesencodings[- if choice !none and choice !'utf- 'tryattachbytes open(filename'rb'read(attachbytes decode(choiceexcept (unicodeerrorlookuperrorioerror)attachesencodings[- 'utf- return bodytextencodingattachesencodings def onsend(self)""threadedmail edit window send button pressmay overlap with any other threaddisables none but quitexit,fail run by threadchecker via queue in after callbackcaveatno progress herebecause send mail call is atomicassumes multiple recipient addrs are separated with ','mailtools module handles encodingsattachmentsdateetcmailtools module also saves sent message text in local file now fully parses to,cc,bcc (in mailtoolsinstead of splitting on the separator naivelycould also use multiline input widgets instead of simple entrybcc added to envelopenot headers unicode encodings of text parts is resolved herebecause it may require gui promptsmailtools performs the actual encoding for parts as needed and requested headers are already decoded in the gui fields hereencoding of any non-ascii headers is performed in mailtoolsnot herebecause no gui interaction is required""resolve unicode encoding for text partsbodytextencodingattachesencodings self resolveunicodeencodings(pymailgui implementation |
5,660 | fieldvalues [entry get(for entry in self hdrfieldsfromtoccsubj fieldvalues[: extrahdrs [('cc'cc)(' -mailer'appname (python)')extrahdrs +list(zip(self userhdrsfieldvalues[ :])bodytext self editor getalltext(split multiple recipient lists on ','fix empty fields tos self splitaddresses(tofor (ix(namevalue)in enumerate(extrahdrs)if valueignored if 'if value ='?'not replaced extrahdrs[ix(name''elif name lower(in ['cc''bcc']split on ',extrahdrs[ix(nameself splitaddresses(value)withdraw to disallow send during send caveatmight not be foolproof user may deiconify if icon visible self withdraw(self getpassword(if neededdon' run pop up in send threadpopup popuputil busyboxnowait(appname'sending message'sendingbusy incr(threadtools startthreadaction self sendmessageargs (fromtossubjextrahdrsbodytextself attachessavemailseparatorbodytextencodingattachesencodings)context (popup,)onexit self onsendexitonfail self onsendfaildef onsendexit(selfpopup)""erase wait windowerase view windowdecr send countsendmessage call auto saves sent message in local filecan' use window addsavedmailsmail text unavailable""popup quit(self destroy(sendingbusy decr(poss when openedin mailconfig sentname os path abspath(mailconfig sentmailfileif sentname in opensavefiles keys()window opensavefiles[sentnamewindow loadmailfilethread(also expands sent file openupdate list,raise def onsendfail(selfexc_infopopup)pop-up errorkeep msg window to save or retryredraw actions frame popup quit(self deiconify(self lift(showerror(appname'send failed\ % \ %sexc_info[: ]printstack(exc_info the pymailgui client |
5,661 | sendingbusy decr(try againenot on self def asksmtppassword(self)""get password if needed from gui herein main threadcaveatmay try this again in thread if no input first timeso goes into loop until input is providedsee pop paswd input logic for nonlooping alternative ""password 'while not passwordprompt ('password for % on % ?(self smtpuserself smtpservername)password popuputil askpasswordwindow(appnamepromptreturn password class replywindow(writewindow)""customize write display for replying text and headers set up by list window ""modelabel 'replyclass forwardwindow(writewindow)""customize reply display for forwarding text and headers set up by list window ""modelabel 'forwardmessagecachemessage cache manager the class in example - implements cache for already loaded messages its logic is split off into this file in order to avoid further complicating list window implementations the server list window creates and embeds an instance of this class to interface with the mail server and to keep track of already loaded mail headers and full text in this versionthe server list window also keeps track of mail fetches in progressto avoid attempting to load the same mail more than once in parallel this task isn' performed herebecause it may require gui operations example - pp \internet\email\pymailgui\messagecache py ""#############################################################################manage message and header loads and contextbut not guia mailfetcherwith list of already loaded headers and messagesthe caller must handle any required threading or gui interfaces changeuse full message text unicode encoding name in local mailconfig moduledecoding happens deep in mailtoolswhen message pymailgui implementation |
5,662 | this may change in future python/emailsee for details changeinherits the new mailconfig fetchlimit feature of mailtoolswhich can be used to limit the maximum number of most recent headers or full mails (if no topfetched on each load requestnote that this feature is independent of the loadfrom used here to limit loads to newly-arrived mails onlythough it is applied at the same timeat most fetchlimit newly-arrived mails are loaded changethough unlikelyit' not impossible that user may trigger new fetch of message that is currently being fetched in threadsimply by clicking the same message again (msg fetchesbut not full index loadsmay overlap with other fetches and sends)this seems to be thread safe herebut can lead to redundant and possibly parallel downloads of the same mail which are pointless and seem odd (selecting all mails and pressing view twice downloads most messages twice!)fixed by keeping track of fetches in progress in the main gui thread so that this overlap is no longer possiblea message being fetched disables any fetch request which it is part ofand parallel fetches are still allowed as long as their targets do not intersect#############################################################################""from pp internet email import mailtools from popuputil import askpasswordwindow class messageinfo""an item in the mail cache list ""def __init__(selfhdrtextsize)self hdrtext hdrtext self fullsize size self fulltext none fulltext is cached msg hdrtext is just the hdrs fulltext=hdrtext if no top class messagecache(mailtools mailfetcher)""keep track of already loaded headers and messagesinherits server transfer methods from mailfetcheruseful in other appsno gui or thread assumptions raw mail text bytes are decoded to str to be parsed with py ' email pkg and saved to filesuses the local mailconfig module' encoding settingdecoding happens automatically in mailtools on fetch""def __init__(self)mailtools mailfetcher __init__(self inherits fetchencoding self msglist [ inherits fetchlimit def loadheaders(selfforcereloadsprogress=none)""three cases to handle herethe initial full load the pymailgui client |
5,663 | don' refetch viewed msgs if hdrs list same or extendedretains cached msgs after delete unless delete fails does quick check to see if msgnums still in sync this is now subject to mailconfig fetchlimit max""if forcereloadsloadfrom self msglist [msg nums have changed elseloadfrom len(self msglist)+ continue from last load only if loading newly arrived if loadfrom ! self checksyncherror(self allhdrs()raises except if bad get all or newly arrived msgs reply self downloadallheaders(progressloadfromheaderslistmsgsizesloadedfull reply for (hdrssizein zip(headerslistmsgsizes)newmsg messageinfo(hdrssizeif loadedfullzip result may be empty newmsg fulltext hdrs got full msg if no 'topself msglist append(newmsgdef getmessage(selfmsgnum)cacheobj self msglist[msgnum- if not cacheobj fulltextfulltext self downloadmessage(msgnumcacheobj fulltext fulltext return cacheobj fulltext get raw msg text add to cache if fetched harmless if threaded simpler coding def getmessages(selfmsgnumsprogress=none)""prefetch full raw text of multiple messagesin thread does quick check to see if msgnums still in syncwe can' get here unless the index list already loaded""self checksyncherror(self allhdrs()raises except if bad nummsgs len(msgnumsadds messages to cache for (ixmsgnumin enumerate(msgnums)some poss already there if progressprogress(ix+ nummsgsonly connects if needed self getmessage(msgnumbut may connect once def getsize(selfmsgnum)return self msglist[msgnum- fullsize encapsulate cache struct it changed once alreadydef isloaded(selfmsgnum)return self msglist[msgnum- fulltext def allhdrs(self)return [msg hdrtext for msg in self msglistdef deletemessages(selfmsgnumsprogress=none)pymailgui implementation |
5,664 | if delete of all msgnums worksremove deleted entries from mail cachebut don' reload either the headers list or already viewed mails textcache list will reflect the changed msg nums on serverif delete fails for any reasoncaller should forceably reload all hdrs nextbecause _some_ server msg nums may have changedin unpredictable ways this now checks msg hdrs to detect out of synch msg numbersif top supported by mail serverruns in thread ""tryself deletemessagessafely(msgnumsself allhdrs()progressexcept mailtools topnotsupportedmailtools mailfetcher deletemessages(selfmsgnumsprogressno errorsupdate index list indexed enumerate(self msglistself msglist [msg for (ixmsgin indexed if ix+ not in msgnumsclass guimessagecache(messagecache)""add any gui-specific calls here so cache usable in non-gui apps ""def setpoppassword(selfappname)""get password from gui herein main thread forceably called from gui to avoid pop ups in threads ""if not self poppasswordprompt 'password for % on % ?(self popuserself popserverself poppassword askpasswordwindow(appnamepromptdef askpoppassword(self)""but don' use gui pop up herei am run in threadwhen tried pop up in threadcaused gui to hangmay be called by mailfetcher superclassbut only if passwd is still empty string due to dialog close ""return self poppassword popuputilgeneral-purpose gui pop ups example - implements handful of utility pop-up windows in modulein case they ever prove useful in other programs note that the same windows utility module is imported hereto give common look-and-feel to the pop ups (iconstitlesand so on the pymailgui client |
5,665 | ""############################################################################utility windows may be useful in other programs ############################################################################""from tkinter import from pp gui tools windows import popupwindow class helppopup(popupwindow)""custom toplevel that shows help text as scrolled text source button runs passed-in callback handler alternativeuse html file and webbrowser module ""myfont 'systemcustomizable mywidth start width def __init__(selfappnamehelptexticonfile=noneshowsource=lambda: )popupwindow __init__(selfappname'help'iconfilefrom tkinter scrolledtext import scrolledtext nonmodal dialog bar frame(selfpack first=clip last bar pack(side=bottomfill=xcode button(barbg='beige'text="source"command=showsourcequit button(barbg='beige'text="cancel"command=self destroycode pack(pady= side=leftquit pack(pady= side=lefttext scrolledtext(selfadd text scrollbar text config(font=self myfonttext config(width=self mywidthtoo big for showinfo text config(bg='steelblue'fg='white'erase on btn or return text insert(' 'helptexttext pack(expand=yesfill=bothself bind(""(lambda eventself destroy())def askpasswordwindow(appnameprompt)""modal dialog to input password string getpass getpass uses stdinnot gui tksimpledialog askstring echos input ""win popupwindow(appname'prompt' configured toplevel label(wintext=promptpack(side=leftentvar stringvar(winent entry(wintextvariable=entvarshow='*'display for input ent pack(side=rightexpand=yesfill=xent bind(''lambda eventwin destroy()ent focus_set()win grab_set()win wait_window(win update(update forces redraw return entvar get(ent widget is now gone pymailgui implementation |
5,666 | ""pop up blocking wait message boxthread waits main gui event thread stays alive during wait but gui is inoperable during this wait stateuses quit redef here because lowernot leftmost""def __init__(selfappnamemessage)popupwindow __init__(selfappname'busy'self protocol('wm_delete_window'lambda: ignore deletes label label(selftext=message 'win quit(to erase label config(height= width= cursor='watch'busy cursor label pack(self makemodal(self messageself label messagelabel def makemodal(self)self focus_set(grab application self grab_set(wait for threadexit def changetext(selfnewtext)self label config(text=self message 'newtextdef quit(self)self destroy(don' verify quit class busyboxnowait(busyboxwait)""pop up nonblocking wait window call changetext to show progressquit to close ""def makemodal(self)pass if __name__ ='__main__'helppopup('spam''see figure \ 'print(askpasswordwindow('spam''enter password')input('enter to exit'pause if clicked wraplinesline split tools the module in example - implements general tools for wrapping long linesat either fixed column or the first delimiter at or before fixed column pymailgui uses this file' wraptext function for text in viewreplyand forward windowsbut this code is potentially useful in other programs run the file as script to watch its self-test code at workand study its functions to see its text-processing logic example - pp \internet\email\pymailgui\wraplines py ""##############################################################################split lines on fixed columns or at delimiters before columnsee alsorelated but different textwrap standard library module ( +) caveatthis assumes strsupporting bytes might help avoid some decodes##############################################################################"" the pymailgui client |
5,667 | def wraplinessimple(lineslistsize=defaultsize)"split at fixed position sizewraplines [for line in lineslistwhile truewraplines append(line[:size]ok if len size line line[size:split without analysis if not linebreak return wraplines def wraplinessmart(lineslistsize=defaultsizedelimiters=,:\ ')"wrap at first delimiter left of sizewraplines [for line in lineslistwhile trueif len(line<sizewraplines +[linebreak elsefor look in range(size- size / - ) need /not if line[lookin delimitersfrontline line[:look+ ]line[look+ :break elsefrontline line[:size]line[size:wraplines +[frontreturn wraplines ##############################################################################common use case utilities ##############################################################################def wraptext (textsize=defaultsize)"when text read all at oncelines text split('\ 'lines wraplinessmart(linessizereturn '\njoin(linesbetter for line-based txtmail keeps original line brks struct split on newlines wrap lines on delimiters put back together def wraptext (textsize=defaultsize)"samebut treat as one long linetext text replace('\ ''lines wraplinessmart([text]sizereturn lines more uniform across lines but loses original line struct drop newlines if any wrap single line on delimiters caller puts back together def wraptext (textsize=defaultsize)"samebut put back togetherlines wraptext (textsizereturn '\njoin(lines'\nwrap as single long line make one string with newlines def wraplines (linessize=defaultsize)"when newline included at endlines [line[:- for line in lineslines wraplinessmart(linessizestrip off newlines (or rstripwrap on delimiters pymailgui implementation |
5,668 | def wraplines (linessize=defaultsize)"samebut concat as one long linetext 'join(lineslines wraptext (textreturn [(line '\ 'for line in linesput them back more uniform across lines but loses original structure put together as line wrap on delimiters put newlines on ends ##############################################################################self-test ##############################################################################if __name__ ='__main__'lines ['spam ham 'spam,ni 'spam ham 'spam,ni 'spam ham ni '''spam'* ''spam ham eggs'sep '- print('all'sepfor line in linesprint(repr(line)print('simple'sepfor line in wraplinessimple(lines)print(repr(line)print('smart'sepfor line in wraplinessmart(lines)print(repr(line)print('single 'sepfor line in wraplinessimple([lines[ ]] )print(repr(line)print('single 'sepfor line in wraplinessmart([lines[ ]] )print(repr(line)print('combined text'sepfor line in wraplines (lines)print(repr(line)print('combined lines'sepprint(wraptext ('\njoin(lines))assert 'join(lines='join(wraplinessimple(lines )assert 'join(lines='join(wraplinessmart(lines )print(len('join(lines))end='print(len('join(wraplinessimple(lines)))end='print(len('join(wraplinessmart(lines)))end='print(len('join(wraplinessmart(lines )))end='input('press enter'pause if clicked html textextracting text from html (prototypepreviewexample - lists the code of the simple-minded html parser that pymailgui uses to extract plain text from mails whose main (or onlytext part is in html form this extracted text is used both for display and for the initial text in replies and forwards the pymailgui client |
5,669 | as before this is prototype because pymailgui is oriented toward plain text todaythis parser is intended as temporary workaround until html viewer/editor widget solution is found because of thatthis is at best first cut which has not been polished to any significant extent robustly parsing html in its entirety is task well beyond the scope of this and book when this parser fails to render good plain text (and it will!)users can still view and cut-and-paste the properly formatted text from the web browser this is also preview html parsing is not covered until of this bookso you'll have to take this on faith until we refer back to it in that later unfortunatelythis feature was added to pymailgui late in the book projectand avoiding this forward reference didn' seem to justify omitting the improvement altogether for more details on html parsingstay tuned for (or flip head to in shortthe class here provides handler methods that receive callbacks from an html parseras tags and their content is recognizedwe use this model here to save text we're interested in along the way besides the parser classwe could also use python' html entities module to map more entity types than are hardcoded here--another tool we will meet in despite its limitationsthis example serves as rough guide to help get you startedand any result it produces is certainly an improvement upon the prior edition' display and quoting of raw html example - pp \internet\email\pymailgui\html text py ""###############################################################*verypreliminary html-to-text extractorfor text to be quoted in replies and forwardsand displayed in the main text display component only used when the main text part is html ( no alternative or other text parts to showwe also need to know if this is html or notbut findmaintext already returns the main text' content type this is mostly provided as first cutto help get you started on more complete solution it hasn' been polishedbecause any result is better than displaying raw htmland it' probably better idea to migrate to an html viewer/editor widget in the future anyhow as ispymailgui is still plain-text biased if (reallywhenthis parser fails to render wellusers can instead view and cut-and-paste from the web browser popped up to display the html see for more on html parsing ###############################################################""from html parser import htmlparser python std lib parser (sax-like modelclass parser(htmlparser)def __init__(self)subclass parserdefine callback methods text assumed to be strany encoding ok pymailgui implementation |
5,670 | self text '[extracted html text]self save self last 'def addtext(selfnew)if self save self text +new self last new def addeoln(selfforce=false)if force or self last !'\ 'self addtext('\ 'def handle_starttag(selftagattrs)others imply content startif tag in (' ''div''table'' '' ''li')self save + self addeoln(elif tag ='td'self addeoln(elif tag ='style'others imply end of priorself save - elif tag ='br'self addeoln(trueelif tag =' 'alts [pair for pair in attrs if pair[ ='alt'if altsnamevalue alts[ self addtext('[value replace('\ '''']'def handle_endtag(selftag)if tag in (' ''div''table'' '' ''li')self save - self addeoln(elif tag ='style'self save + def handle_data(selfdata)data data replace('\ '''data data replace('\ ''if data !len(data)self addtext(datawhat about def handle_entityref(selfname)xlate dict(lt=''amp='&'nbsp=''get(name'?'if xlateself addtext(xlateplus many othersshow as is def html text(text)tryhp parser(hp feed(textreturn(hp textexceptreturn text the pymailgui client |
5,671 | to test mehtml text py media\html text-test\htmlmail html parse file name in commandlinedisplay result in tkinter text file assumed to be in unicode platform defaultbut text need not be import systkinter text open(sys argv[ ]' 'read(text html text(textt tkinter text( insert(' 'textt pack( mainloop(after this example and had been written and finalizedi did search for html-to-text translators on the web to try to find better optionsand discovered python-coded solution which is much more complete and robust than the simple prototype script here regrettablyi also discovered that this system is named the same as the script listed herethis was unintentional and unforeseen (alasdevelopers are predisposed to think alikefor details on this more widely tested and much better alternativesearch the web for html text it' open sourcebut follows the gpl licenseand is available only for python at this writing ( it uses the sgmllib which has been removed in favor of the new html parser in xunfortunatelyits gpl license may raise copyright concerns if shipped with pymailgui in this book' example package or otherwiseworseits status means it cannot be used at all with this book' examples today there are additional plain-text extractor options on the web worth checking outincluding beautifulsoup and yet another named html text py (noreally!they also appear to be available for just todaythough naturallythis story may change by the time you read this note there' no reason to reinvent the wheelunless existing wheels don' fit your cartmailconfiguser configurations in example - pymailgui' mailconfig user settings module is listed this program has its own version of this module because many of its settings are unique for pymailgui to use the program for reading your own emailset its initial variables to reflect your pop and smtp server names and login parameters the variables in this module also allow the user to tailor the appearance and operation of the program without finding and editing actual program logic as isthis is single-account configuration we could generalize this module' code to allow for multiple email accountsselected by input at the console when first importedpymailgui implementation |
5,672 | extended externally example - pp \internet\email\pymailgui\mailconfig py ""###############################################################################pymailgui user configuration settings email scripts get their server names and other email config options from this modulechange me to reflect your machine namessigand preferences this module also specifies some widget style preferences applied to the guias well as message unicode encoding policy and more in version see alsolocal textconfig pyfor customizing pyedit pop-ups made by pymailgui warningpymailgui won' run without most variables heremake backup copycaveatsomewhere along the way this started using mixed case inconsistently tbdwe could get some user settings from the command line tooand configure dialog gui would be betterbut this common module file suffices for now ###############################################################################""#(required for loaddeletepop email server machineuser##popservername '?please set your mailconfig py attributes?popservername 'pop secureserver netpopusername 'pp @learning-python comsee altconfigsfor others #(required for sendsmtp email server machine namesee python smtpd module for smtp server class to run locally ('localhost')noteyour isp may require that you be directly connected to their systemi once could email through earthlink on dial upbut not via comcast cable#smtpservername 'smtpout secureserver net#(optionalpersonal information used by pymailgui to fill in edit formsif not setdoes not fill in initial form valuessignature -can be triple-quoted blockignored if empty stringaddress -used for initial value of "fromfield if not emptyno longer tries to guess from for replies--varying success#myaddress 'pp @learning-python commysignature ('thanks,\ '--mark lutz (#(may be required for sendsmtp user/password if authenticatedset user to none or 'if no login/authentication is requiredand set the pymailgui client |
5,673 | force programs to ask (in consoleor gui#smtpuser none smtppasswdfile 'per your isp set to 'to be asked #smtpuser popusername #(optionalpymailguiname of local one-line text file with your pop passwordif empty or file cannot be readpswd is requested when first connectingpswd not encryptedleave this empty on shared machinespymailcgi always asks for pswd (runs on possibly remote server)#poppasswdfile ' :\temp\pymailgui txtset to 'to be asked #(requiredlocal file where sent messages are always savedpymailgui 'openbutton allows this file to be opened and vieweddon' use form if may be run from another dire pp demos ##sentmailfile \sentmail txtmeans in current working dir #sourcedir ' :\pp \internet\email\pymailgui\#sentmailfile sourcedir 'sentmail txtdetermine automatically from one of my source files import wraplinesos mysourcedir os path dirname(os path abspath(wraplines __file__)sentmailfile os path join(mysourcedir'sentmail txt'#(defunctlocal file where pymail saves pop mail (full text)pymailgui instead asks for name in gui with pop-up dialogalso asks for split directoryand part buttons save in /tempparts##savemailfile ' :\temp\savemail txtnot used in pymailguidialog #(optionalcustomize headers displayed in pymailgui list and view windowslistheaders replaces defaultviewheaders extends itboth must be tuple of stringsor none to use default hdrs#listheaders ('subject''from''date''to'' -mailer'viewheaders ('bcc',#(optionalpymailgui fonts and colors for text server/file message list windowsmessage content view windowsand view window attachment buttonsuse ('family'size'style'for font'colornameor hexstr '#rrggbbfor pymailgui implementation |
5,674 | view windows can also be set interactively with texteditor' tools menusee also the setcolor py example in the gui part (ch for custom colors#listbg 'indianredlistfg 'blacklistfont ('courier' 'bold'viewbg 'light blueviewfg 'blackviewfont ('courier' 'bold'viewheight partfg partbg none'white''#rrggbbnone('courier' 'bold italic'use fixed-width font for list columns was '#dbbedcmax lines for height when opened ( none none see tk color namesaquamarine paleturquoise powderblue goldenrod burgundy #listbg listfg listfont none #viewbg viewfg viewfont viewheight none to use defaults #partbg partfg none #(optionalcolumn at which mail' original text should be wrapped for viewreplyand forwardwraps at first delimiter to left of this positioncomposed text is not auto-wrappeduser or recipient' mail tool must wrap new text if desiredto disable wrappingset this to high value ( ?)#wrapsz #(optionalcontrol how pymailgui opens mail parts in the guifor view window split actions and attachment quick-access buttonsif not okaytoopenpartsquick-access part buttons will not appear in the guiand split saves parts in directory but does not open themverifypartopens used by both split action and quick-access buttonsall known-type parts open automatically on split if this set to falseverifyhtmltextopen used by web browser open of html main text part#okaytoopenparts true verifypartopens false verifyhtmltextopen false open any parts/attachments at allask permission before opening each partif main text part is htmlask before open#(optionalthe maximum number of quick-access mail part buttons to show in the middle of view windowsafter this manya button will be displayedwhich runs the "splitaction to extract additional parts#maxpartbuttons how many part buttons in view windows ** additions follow ** the pymailgui client |
5,675 | bytesand to encode and decode message text stored in text-mode save filessee the book' for detailsthis is limited and temporary approach to unicode encodings until new bytes-friendly email package parser is provided which can handle unicode encodings more accurately on message-level basisnote'latin (an -bit encoding which is superset of -bit asciiwas required to decode message in some old email save files hadnot 'utf '#fetchencoding 'latin- how to decode and store full message text (ascii?#(optionalfor sendunicode encodings for composed mail' main text plus all text attachmentsset these to none to be prompted for encodings on mail sendelse uses values here across entire sessiondefault='latin- if gui cancelin all casesfalls back on utf- if your encoding setting or input does not work for the text being sent ( ascii chosen for reply to non-ascii textor non-ascii attachments)the email package is pickier than python about nameslatin- is known (uses qp mime)but latin isn' (uses base mime)set these to sys getdefaultencoding(result to choose the platform defaultencodings of text parts of fetched email are automatic via message headers#maintextencoding 'asciiattachmenttextencoding 'asciimain mail body text part sent (none=askall text part attachments sent (utf- latin- #(optionalfor sendset this to unicode encoding name to be applied to non-ascii headersas well as non-ascii names in email addresses in headersin composed messages when they are sentnone means use the utf- defaultwhich should work for most use casesemail names that fail to decode are dropped (the address part is used)note that header decoding is performed automatically for displayaccording to header contentnot user setting#headersencodeto none how to encode non-ascii headers sent (none=utf- #(optionalselect texthtmlor both versions of the help documentalways shows one or the otherdisplays html if both of these are turned off #showhelpastext true showhelpashtml true scrolled textwith button for opening source files html in web browserwithout source file links #(optionalif truedon' show selected html text message part in pyedit popup too if it is being displayed in web browserif false show bothto see unicode encoding name and effect in text widget (browser may not know)#skiptextonhtmlpart false don' show html part in pyedit popup too pymailgui implementation |
5,676 | downloaded on each load requestgiven this setting npymailgui fetches at most of the most recently arrived mailsolder mails outside this set are not fetched from the serverbut are displayed as empty/dummy emailsif this is assigned to none (or )loads will have no such limituse this if you have very many mails in your inboxand your internet or mail server speed makes full loads too slow to be practicalpymailgui also loads only newly-arrived headersbut this setting is independent of that feature#fetchlimit maximum number headers/emails to fetch on loads #(optionalinitial widthheight of mail index lists (chars lines)just conveniencesince the window can be resized/expanded freely once opened#listwidth none listheight none none use default none use default #(optionalfor replyif truethe reply operation prefills the reply' cc with all original mail recipientsafter removing duplicates and the new senderif falseno cc prefill occursand the reply is configured to reply to the original sender onlythe cc line may always be edited laterin either case #repliescopytoall true true=reply to sender all recipientselse sender #end textconfigcustomizing pop-up pyedit windows the prior section' mailconfig module provides user settings for tailoring the pyedit component used to view and edit main mail textbut pymailgui also uses pyedit to display other kinds of pop-up textincluding raw mail textsome text attachmentsand source code in its help system to customize display for these pop upspymailgui relies on pyedit' own utilitywhich attempts to load module like that in example - from the client application' own directory by contrastpyedit' unicode settings are loaded from the single textconfig module in its own package' directory since they are not expected to vary across platform (see for more detailsexample - pp \internet\email\pymailgui\textconfig py ""customize pyedit pop-up windows other than the main mail text componentthis module (not its packageis assumed to be on the path for these settingspyedit unicode settings come from its own package' textconfig pynot this""bg 'beigefg 'black the pymailgui client absent=whitecolorname or rgb hexstr absent=blacke 'beige''# |
5,677 | font ('courier' 'normal'height tk default lines width tk default characters pymailguihelpuser help text and display finallyexample - lists the module that defines the text displayed in pymailgui' help pop up as one triple-quoted stringas well as function for displaying the html rendition of this text the html version of help itself is in separate file not listed in full here but included in the book' examples package in facti've omitted most of the help text stringtooto conserve space here (it spanned pages in the prior editionand would be longer in this one!for the full storysee this module in the examples packageor run pymailgui live and click the help bar at the top of its main server list window to learn more about how pymailgui' interface operates if factyou probably shouldthe help display may explain some properties of pymailgui not introduced by the demo and other material earlier in this the html rendition of help includes section linksand is popped up in web browser because the text version also is able to pop up source files and minimizes external dependencies (html fails if no browser can be located)both the text and html versions are provided and selected by users in the mailconfig module other schemes are possible ( converting html to text by parsing as fallback option)but they are left as suggested improvements example - pp \internet\pymailgui\pymailguihelp py (partial""#########################################################################pymailgui help text string and html display functionhistorythis display began as an info box pop up which had to be narrow for linuxit later grew to use scrolledtext with buttons insteadit now also displays an html rendition in web browserethe help string is stored in this separate module to avoid distracting from executable code as codedwe throw up this text in simple scrollable text boxin the futurewe might instead use an html file opened with browser (use webbrowser moduleor run "browser help htmlor dos "start help htmlwith os system)ethe help text is now also popped up in web browser in html formwith listssection linksand separatorssee the html file pymailguihelp html in the examples package for the simple html translation of the help text string herepopped up in browserboth the scrolled text widget and html browser forms are currently supportedchange mailconfig py to use the flavor(syou prefer#########################################################################""pymailgui implementation |
5,678 | helpfile 'pymailguihelp htmlsee book examples package def showhtmlhelp(helpfile=helpfile)"" popup html version of help file in local web browser via webbrowserthis module is importablebut html file might not be in current working dir ""import oswebbrowser mydir os path dirname(__file__dir of this module' filename mydir os path abspath(mydirmake absolutemay be etc webbrowser open_new('file://os path join(mydirhelpfile)#########################################################################string for older text displayclient responsible for gui construction #########################################################################helptext """pymailguiversion may ( january programming python th edition mark lutzfor 'reilly mediainc pymailgui is multiwindow interface for processing emailboth online and offline its main interfaces include one list window for the mail serverzero or more list windows for mail save filesand multiple view windows for composing or viewing emails selected in list window on startupthe main (serverlist window appears firstbut no mail server connection is attempted until load or message send request all pymailgui windows may be resizedwhich is especially useful in list windows to see additional columns noteto use pymailgui to read and write email of your ownyou must change the pop and smtp server names and login details in the file mailconfig pylocated in pymailgui' source-code directory see section for details contents version enhancements list window actions view window actions offline processing viewing text and attachments sending text and attachments mail transfer overlap mail deletion inbox message number synchronization loading email unicode and internationalization support the mailconfig configuration module dependencies miscellaneous hints ("cheat sheet"rest of file omitted miscellaneous hints ("cheat sheet" the pymailgui client |
5,679 | addresses may be given in the full '"nameform payloads and headers are decoded on fetches and encoded on sends html mails show extracted plain text plus html in web browser toccand bcc receive composed mailbut no bcc header is sent if enabled in mailconfigbcc is prefilled with sender address reply and fwd automatically quote the original mail text if enabledreplies prefill cc with all original recipients attachments may be added for sends and are encoded as required attachments may be opened after view via split or part buttons double-click mail in the list index to view its raw text select multiple mails to process as setctrl|shift clickor all sent mails are saved to file named in mailconfiguse open to view save pops up dialog for selecting file to hold saved mails save always appends to the chosen save filerather than erasing it split asks for save directorypart buttons save in /tempparts open and save dialogs always remember the prior directory use text editor' save to save draft of email text being composed passwords are requested if/when neededand not stored by pymailgui you may list your password in file named in mailconfig py to print emails"saveto text file and print with other tools see the altconfigs directory for using with multiple email accounts emails are never deleted from the mail server automatically delete does not reload message headersunless it fails delete checks your inbox to make sure it deletes the correct mail fetches detect inbox changes and may automatically reload the index any number of sends and disjoint fetches may overlap in time click this window' source button to view pymailgui source-code files watch this is an open source systemchange its code as you like ""if __name__ ='__main__'print(helptextinput('press enter key'to stdout if run alone pause in dos console pop ups see the examples package for the html help filethe first few lines of which are shown in example - it' simple translation of the module' help text string (adding bit more pizzazz to this page is left in the suggested exercise columnexample - pp \internet\pymailgui\pymailguihelp html (partialpymailgui help pymailguiversion pymailgui implementation |
5,680 | programming python th edition mark lutzfor 'reilly mediainc pymailgui is multiwindow interface for processing emailboth online and rest of file omitted altconfigsconfiguring for multiple accounts though not an "officialpart of the systemi use few additional short files to launch and test it if you have multiple email accountsit can be inconvenient to change configuration file every time you want to open one in particular moreoverif you open multiple pymailgui sessions for your accounts at the same timeit would be better if they could use custom appearance and behavior schemes to make them distinct to address thisthe altconfigs directory in the examples source directory provides simple way to select an account and configurations for it at start-up time it defines new top-level script which tailors the module import search pathalong with mail config that prompts for and loads custom configuration module whose suffix is named by console input launcher script is also provided to run without module search path configurations--from pygadgets or desktop shortcutfor examplewithout requiring pythonpath settings for the pp root examples - through - list the files involved example - pp \internet\pymailgui\altconfigs\pymailgui py import sys sys path insert( 'exec(open(/pymailgui py'read()\pymailgui py or 'bookfor book configs add visibility for real dir do thisbut get mailconfig here example - pp \internet\pymailgui\altconfigs\mailconfig py above open(/mailconfig py'read(open('mailconfig_book py'' 'write(aboveacct input('account name?'exec('from mailconfig_% import *acctcopy version above here (hack?used for 'bookand as othersbase bookrmitrain is first on sys path example - pp \internet\pymailgui\altconfigs\mailconfig_rmi py from mailconfig_book import popservername 'pop rmi netpopusername 'lutzmyaddress 'lutz@rmi netlistbg 'navylistfg 'whitelistheight higher initially viewbg '#dbbedcviewfg 'blackwrapsz wrap at cols fetchlimit load more headers the pymailgui client get base in (copied from this is big inbox emails |
5,681 | from mailconfig_book import popusername 'lutz@learning-python commyaddress 'lutz@learning-python comlistbg 'wheatlistfg 'navyviewbg 'aquamarineviewfg 'blackwrapsz viewheaders none no bcc fetchlimit load more headers get base in (copied from goldenroddark greenbeige chocolatebrownexample - pp \internet\pymailgui\altconfigs\launch_pymailgui py to run without pythonpath setup ( desktopimport os launcher py is overkill os environ['pythonpath'rhmmgeneralize me os system('pymailgui py'inherits path env var account files like those in examples - and - can import the base "bookmodule (to extend itor not (to replace it entirelyto use these alternative account configurationsrun command line like the following or run the self-configuring launcher script in example - from any location either wayyou can open these account' windows to view the included saved mailsbut be sure to change configurations for your own email accounts and preferences first if you wish to fetch or send mail from these clientsc:\pp \internet\email\pymailgui\altconfigspymailgui py account name?rmi add "startto the beginning of this command to keep your console alive on windows so you can open multiple accounts (try "&at the end on unixfigure - earlier shows the scene with all three of my accounts open in pymailgui keep them open perpetually on my desktopsince load fetches just newly arrived headers no matter how long the gui may have sat dormantand send requires nothing to be loaded at all while they're openthe alternative color schemes make the accountswindows distinct desktop shortcut to the launcher script makes opening my accounts even easier as isaccount names are only requested when this special pymailgui py file is run directlyand not when the original file is run directly or by program launchers (in which case there may be no stdin to readextending module like mailconfig which might be imported in multiple places this way turns out to be an interesting task (which is largely why don' consider its quick solution here to be an official end-user featurefor instancethere are other ways to allow for multiple accountsincludingchanging the single mailconfig module in-place importing alternative modules and storing them as key "mailconfigin sys modules pymailgui implementation |
5,682 | setattr using class for configuration to better support customization in subclasses issuing pop-up in the gui to prompt for an account name after or before the main window appears and so on the separate subdirectory scheme used here was chosen to minimize impacts on existing code in generalto avoid changes to the existing mailconfig module specifically (which works fine for the single account case)to avoid requiring extra user input of any kind in single account casesand to allow for the fact that an "import module as module statement doesn' prevent "module from being imported directly later this last point is more fraught with peril than you might expect--importing customized version of module is not merely matter of using the "asrenaming extensionimport as print( attrcustom importload as alternative prints attr in py import print( attrlater importsloads py anyhowprints attr in py in other wordsthis is quick-and-dirty solution that originally wrote for testing purposesand it seems prime candidate for improvement--along with the other ideas in the next section' wrap up ideas for improvement although use the version of pymailgui as is on regular basis for both personal and business communicationsthere is always room for improvement to softwareand this system is no exception if you wish to experiment with its codehere are few suggested projects to close out this column sorts and list layout mail list windows could be sorted by columns on demand this may require more sophisticated list window structure which presents columns more distinctly the current display of mail lists seems like the most obvious candidate for cosmetic upgrade in generaland any column sorting solution would likely address this as well tkinter extensions such as the tix hlist widget may show promise hereand the third-party tkintertreectrl supports multicolumn sortable listboxestoobut is available only for python todayconsult the web and other resources for pointers and details mail save file (and sent filesize the implementation of save-mail files limits their size by loading them into memory all at oncea dbm keyed-access implementation may work around this constraint see the list windows module comments for ideas this also applies to sent-mail the pymailgui client |
5,683 | also benefit from prompt for deletions if they grow too large embedded links hyperlink urls within messages could be highlighted visually and made to spawn web browser automatically when clicked by using the launcher tools we met in the gui and system parts of this book (tkinter' text widget supports links directlyhelp text redundancy in this versionthe help text had grown so large that it is also implemented as html and displayed in web browser using python' webbrowser module (instead of or in addition to textper mailconfig settingsthat means there are currently two copies of the basic help textsimple text and html this is less than ideal from maintenance perspective going forward we may want to either drop the simple text version altogetheror attempt to extract the simple text from the html with python' html parser module to avoid redundant copiessee for more on html parsing in generaland see pymailgui' new html text module for plain-text extraction tool prototype the html help version also does not include links to display source filesthese could be inserted into the html automatically with string formattingthough it' not clear what all browsers will do with python source code (some may try to run itmore threading contexts message save and split file writes could also be threaded for worst-case scenarios for pointers on making saves parallelsee the comments in the file class of list windows pythere may be some subtle issues that require both thread locks and general file locking for potentially concurrent updates list window index fills might also be threaded for pathologically large mailboxes and woefully slow machines (optimizing to avoid reparsing headers may help heretooattachment list deletes there is currently no way to delete an attachment once it has been added in compose windows this might be supported by adding quick-access part buttons to compose windowstoowhich could verify and delete the part when clicked spam filtering we could add an automatic spam filter for mails fetchedin addition to any provided at the email server or isp the python-based spambayes might help this is often better implemented by servers than clientsbut not all isps filter spam improve multiple account usage per the prior sectionthe current system selects one of multiple email accounts and uses its corresponding mail configuration module by running special code in the altconfigs subdirectory this works for book examplebut it would be fairly straightforward to improve for broader audiences ideas for improvement |
5,684 | we may want to add an explicit button for opening the sent-mails file pymailgui already does save sent messages to text file automaticallywhich may be opened currently with the list window' open button franklythoughthis feature may be too-well-kept secret-- forgot about it myself when revisited the program for this editionit might also be useful to allow sent-mail saves to be disabled in mailconfig for users who might never delete from this file (it can grow large fairly quicklysee the earlier prompt-for-deletion suggestion as wellthread queue speed tuning as mentioned when describing version changesthe thread queue has been sped up by as much as factor of in this version to quicken initial header downloads this is achieved both by running more than one callback per timer event and scheduling timer events to occur twice as often as before checking the queue too oftenhowevermight increase cpu utilization beyond acceptable levels on some machines on my windows laptopthis overhead is negligible (the program' cpu utilization is when idle)but you may want to tune this if it' significant on your platform see the list windows code for speed settingsand threadtools py in for the base code in generalincreasing the number of callbacks per event and decreasing timer frequency will decrease cpu drain without sacrificing responsiveness (and if had nickel for every time said that mailing lists we could add support for mailing listsallowing users to associate multiple email addresses with saved list name on sends to list namethe mail would be sent to all on the list (the to addresses passed to smtplib)but the email list could be used for the email' to header line see ' smtp coverage for mailing list-related examples html main text views and edits pymailgui is still oriented toward supporting only plain text for the main text of messagedespite the fact that some mailers today are more html-biased in this regard this partly stems from the fact that pymailgui uses simple tkinter text widget for main text composition pymailgui can display such messageshtml in popped-up web browserand it attempts to extract text from the html for display per the next notebut it doesn' come with its own html editor fully supporting html for main message text will likely require tkinter extension (orregrettablya port to another gui toolkit with working support for this featurehtml parser honing on related noteas described earlierthis version includes simple-minded html parserapplied to extract text from html main (or onlytext parts when they are displayed or quoted in replies and forwards as also mentioned earlierthis parser is nowhere near complete or robustfor production-level qualitythis would have to be improved by testing over large set of html emails better yet the pymailgui client |
5,685 | source alternativessuch as the html text py same-named third-party utility described in this earlier note the open source beautifulsoup system offers another lenient and forgiving html parserbut is based on sgmlparser tools available in only (removed in xtext/html alternative mails also in the html departmentthere is presently no support for sending both text and html versions of mail as mime multipart/alternative message-- popular scheme which supports both textand html-based clients and allows users to choose which to use such messages can be viewed (both parts are offered in the gui)but cannot be composed againsince there is no support for html editing anyhowthis is moot pointif such an editor is ever addedwe' need to support this sort of mail structure in mailtools message object construction code and refactor parts of its current send logic so that it can be shared internationalized headers throw list columns off as is so often true in softwareone feature added in this version broke another already presentthe fonts used for display of some non-ascii unicode header fields is large enough to throw off the fixed-width columns in mail index list windows they rely on the assumption that characters is always the same width among all mailsand this is no longer true for some chinese and other character set encodings this isn' showstopper--it only occurs when some headers are displayedand simply means that "|column separators are askew for such mails onlybut could still be addressed the fix here is probably to move to more sophisticated list displayand might be resolved as side effect of allowing for the column sorts described earlier address books pymailgui has no notion of automatically filling in an email address from an address bookas many modern email clients do adding this would be an interesting extensionlow-level keyboard event binding may allow matching as addresses are typedand python' pickle and shelve modules of and might come in handy for data storage spelling checker there is currently no spelling checker of the sort most email programs have today this could be added in pymailguibut it would probably be more appropriate to add it in the pyedit text edit component/program that it usesso the spell-checking would be inherited by all pyedit clients quick web search reveals variety of optionsincluding the interesting pyenchant third-party packagenone of which we have space to explore here mail searches similarlythere is no support for searching emailscontent (headers or bodiesfor given string it' not clear how this should be provided given that the system fetches and caches just message headers until mail is requestedbut searching ideas for improvement |
5,686 | save to store fetched mails in text file and searching in that file externally frozen binary distribution as desktop programpymailgui seems an ideal candidate for packing as selfcontained frozen binary executableusing tools such as pyinstallerpy exeand others when distributed this wayusers need not install pythonsince the python runtime is embedded in the executable selecting reply versus reply-all in the gui as described in the changes overview earlierin this versionreply by default now copies all the original mail' recipients by prefilling the cc linein addition to replying to the original sender this cc feature can be turned off in mailconfig because it may not be desirable in all cases ideallythoughthis should be selectable in the gui on mail-by-mail basisnot per session adding another button to list windows for replyall would sufficesince this feature was added too late in this project for gui changesthoughthis will have to be relegated to the domain of suggested exercise propagating attachmentswhen replying to or forwarding an emailpymailgui discards any attachments on the original message this is by designpartly because there is currently no way to delete attached parts in the gui prior to sending (you couldn' remove selectively and couldn' remove all)and partly because this system' current sole user prefers to work this way users can work around this by running split to save all parts in directoryand then adding any desired attachments to the mail from there stillit might be better to allow the user to choose that this happen automatically for replies and forwards similarlyforwarding html mails well currently requires saving and attaching the html part to avoid quoting the textthis might be similarly addressed by parts propagation in general disable editing for viewed mailsmail text is editable in message view windowseven though new mail is not being composed this is deliberate--users can annotate the message' text and save it in text file with the save button at the bottom of the windowor simply cut-andpaste portions of it into other windows this might be confusingthoughand is redundant (we can also edit and save by clicking on the main text' quick-access part buttonremoving edit tools would require extending pyedit using pyedit for display in general is useful design--users also have access to all of pyedit' tools for the mail textincluding savefindgotogrepreplaceundo/redoand sothough edits might be superfluous in this context automatic periodic new mail checkit would be straightforward to add the ability to automatically check for and fetch new incoming email periodicallyby registering long-duration timer events with either the after widget method or the threading module' timer object haven' the pymailgui client |
5,687 | your mileage may vary reply and forward buttons on view windowstoominor potential ergonomic improvementwe could include reply and forward buttons on the message view windowstooinstead of requiring these operations to be selected in mail list windows only as this system' sole useri prefer the uncluttered appearance and conceptual simplicity of the current latter approachguis have way of getting out of hand when persistent pop-up windows start nesting too deeply it would be trivial to have reply/forward on view windowstoothoughthey could probably fetch mail components straight from the gui instead of reparsing message omit bcc header in view windowsminor nitmail view windows may be better off omitting the bcc header even if it' enabled in the configuration file since it shouldn' be present once mail is sentit really needs to be included in composition windows only it' displayed as is anyhowto verify that bcc is omitted on sends (the prior edition did not)to maintain uniform look for all mail windowsto avoid special-casing this in the codeand to avoid making such ergonomic decisions in the absence of actual user feedback check for empty subject linesminor usability issueit would be straightforward to add check for an empty subject field on sends and to pop up verification dialog to give the user second chance to fill the field in blank subject is probably unintended we could do the same for the to field as wellthough there may be valid use cases for omitting this from mail headers (the mail is still sent to cc and bcc recipientsremoving duplicate recipients more accuratelyas isthe send operation attempts to remove duplicate recipients using set operations this worksbut it may be inaccurate if the same email address appears twice with different name component ( "name name "to do betterwe could fully parse the recipient addresses to extract and compare just the address portion of the full email address arguablythoughit' not clear what should be done if the same recipient address appears with different names could multiple people be using the same email accountif notwhich name should we choose to usefor nowend user or mail server intervention may be required in the rare cases where this might crop up in most casesother email clients will likely handle names in consistent ways that make this moot point on related notesreply removes duplicates in cc prefills in the same simplistic wayand both sends and replies could use case-insensitive string comparisons when filtering for duplicates handling newsgroup messagestoobecause internet newsgroup posts are similar in structure to emails (header lines plus body textsee the nntplib example in )this script could in principle ideas for improvement |
5,688 | mutation as clever generalization or diabolical hack is left as an exercise in itself smtp sends may not work in some network configurationson my home/office networksmtp works fine and as shown for sending emailsbut have occasionally seen sends have issues on public networks of the sort available in hotels and airports in some casesmail sends can fail with exceptions and error messages in the guiin worst casessuch sends might fail with no exception at all and without reporting an error in the gui the mail simply goes nowherewhich is obviously less than ideal if its content matters it' not clear if these issues are related to limitations of the networks usedof python' smtplibor of the isp-provided smtp server use unfortunatelyi ran out of time to recreate the problem and investigate further (againa system with single user also has just single testerresolving any such issues is left as an exercise for the readerbut as cautionif you wish to use the system to send important emailsyou should first test sends in new network environment to ensure that they will be routed correctly sending an email to yourself and verifying receipt should suffice performance tuningalmost all of the work done on this system to date has been related to its functionality the system does allow some operation threads to run in paralleland optimizes mail downloads by fetching just headers initially and caching alreadyfetched full mail text to avoid refetching apart from thisthoughits performance in terms of cpu utilization and memory requirements has not been explored in any meaningful way at all that' for the best--in general we code for utility and clarity first in pythonand deal with performance later if and only if needed having said thata broader audience for this program might mandate some performance analysis and improvement for examplealthough the full text of fetched mails is kept just once in cacheeach open view of message retains copy of the parsed mail in memory for large mailsthis may impact memory growth caching parsed mails as well might help decrease memory footprintsthough these will still not be small for large mailsand the cache might hold onto memory longer than required if not intelligently designed storing messages or their parts in files (perhaps as pickled objectsinstead of in memory might alleviate some growthtoothough that may also require mechanism for reaping temporary files as ispython' garbage collector should reclaim all such message space eventually as windows are closedbut this can depend upon how and where we retain object references see also the gc standard library modules for possible pointers on finer-grained garbage collection control unicode model tuningas discussed in brief at the start of this and in full in pymailgui' support for unicode encoding of message text and header components is broadbut not necessarily as general or universally applicable as it might be some the pymailgui client |
5,689 | python upon which pymailgui heavily depends it may be difficult for pythoncoded email clients to support some features better until python' libraries dotoo moreoverthe unicode support that is present in this program has been tested neither widely nor rigorously just like ' pyeditthis is currently still single-user system designed to work as book examplenot an open source project because of thatsome of the current unicode policies are partially heuristic in nature and may have to be honed with time and practice for exampleit may prove better in the end to use utf- encoding (or none at allfor sends in generalinstead of supporting some of the many user options which are included in this book for illustration purposes since utf- can represent most unicode code pointsit' broadly applicable more subtlywe might also consider propagating the main text part' unicode encoding to the embedded pyedit component in view and edit windowsso it can be used as known encoding by the pyedit save button as isusers can pop up the main text' part in view windows to save with known encoding automaticallybut saves of drafts for mails being edited fall back on pyedit' own unicode policies and gui prompts the ambiguous encoding for saved drafts may be unavoidablethough--users might enter characters from any character setboth while writing new mails from scratch and while editing the text of replies and forwards (just like headers in replies and forwardsthe initial known encoding of the original main text part may no longer apply after arbitrary editsin additionthere is no support for non-ascii encodings of full mail textit' not impossible that encoded text might appear in other contexts in rare emails ( in attachment filenameswhose undecoded form may or may not be valid on the receiving platform' filesystemand may require renaming if allowed at all)and although internationalization is supported for mail contentthe gui itself still uses english for its buttonslabelsand titles--something that truly locationneutral program may wish to address in other wordsif this program were to ever take the leap to commercial-grade or broadly used softwareits unicode story would probably have to be revisited also discussed in future release of the email package may solve some unicode issues automaticallythough pymailgui may also require updates for the solutionsas well as for incompatibilities introduced by them for nowthis will have to stand as useful object lesson in itselffor both better and worsesuch changes will always be fact of life in the constantly evolving world of software development and so on--because this software is open sourceit is also necessarily open-ended ultimatelywriting complete email client is substantial undertakingand we've taken this example as far as we can in this book to move pymailgui further alongwe' probably have to consider the suitability of both the underlying python ideas for improvement |
5,690 | we've implemented herebut they might limit further progress for examplethe current lack of an html viewer widget in the base tkinter toolkit precludes html mail viewing and composition in the gui itself moreoveralthough pymailgui broadly supports internationalization todayit must rely on workarounds to get email to work at all to be fairsome of the email package' issues described in this book will likely be fixed by the time you read about themand email in general is probably close to worst case for internationalization issues brought into the spotlight by unicode prominence in python stillsuch tool constraints might impede further system evolution on the other handdespite any limitations in the tools it deployspymailgui does achieve all its goals--it' an arguably full-featured and remarkably quick desktop email clientwhich works surprisingly well for my emails and preferences and performs admirably on the cases 've tested to date it may not satisfy your tastes or constraintsbut it is open to customization and imitation suggested exercises and further tweaking are therefore officially delegated to your imaginationthis is pythonafter all this concludes our tour of python client-side protocols programming in the next 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 previous 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 world viewthoughwe need to explore the server realmtoo the pymailgui client |
5,691 | server-side scripting "ohwhat tangled web we weavethis is the fourth part of our look at python internet programming in the last three we explored sockets and basic client-side programming interfaces such as ftp and email in this our main focus will be on writing server-side scripts in python-- type of program usually referred to as cgi scripts though something of lowest common denominator for web development todaysuch scripts still provide simple way to get started with implementing interactive websites in python server-side scripting and its derivatives are at the heart of much of the interaction that happens on the web this is true both when scripting manually with cgi and when using the higher-level frameworks that automate some of the work because of thatthe fundamental web model we'll explore here in the context of cgi scripting is prerequisite knowledge for programming the web wellregardless of the tools you choose to deploy as we'll seepython is an ideal language for writing scripts to implement and customize websitesbecause of both its ease of use and its library support in the following we will use the basics we learn in this to implement full-blown website hereour goal is to understand the fundamentals of server-side scriptingbefore exploring systems that deploy or build upon that basic model house upon the sand as you read the next two of this bookplease keep in mind that they focus on the fundamentals of server-side scripting and are intended only as an introduction to programming in this domain with python the web domain is large and complexchanges rapidly and constantlyand often prescribes many ways to accomplish given goal--some of which can vary from browser to browser and server to server for instancethe password encryption scheme of the next may be unnecessary under certain scenarios (with suitable serverwe could use secure http insteadmoreoversome of the html we'll use here may not leverage all of that language' |
5,692 | material added in later editions of this book reflects recent technology shifts in this domain given such large and dynamic fieldthis part of the book does not even pretend to be complete look at the server-side scripting domain that isyou should not take this text to be final word on the subject to become truly proficient in this areayou should also expect to spend some time studying other texts for additional webmaster- details and techniques--for examplechuck musciano and bill kennedy' html xhtmlthe definitive guide ( 'reillythe good news is that here you will explore the core ideas behind server-side programmingmeet python' cgi tool setand learn enough to start writing substantial websites of your own in python this knowledge should apply to wherever the web or you head next what' server-side cgi scriptsimply putcgi scripts implement much of the interaction you typically experience on the web they are standard and widely used mechanism for programming webbased systems and website interactionand they underlie most of the larger web development models there are other ways to add interactive behavior to websites with pythonboth on the client and the server we briefly met some such alternatives near the start of for instanceclient-side solutions include jython appletsrias such as silverlight and pyjamasactive scripting on windowsand the emerging html standard on the server sidethere are variety of additional technologies that build on the basic cgi modelsuch as python server pagesand web frameworks such as djangoapp enginecherrypyand zopemany of which utilize the mvc programming model by and largethoughcgi server-side scripts are used to program much of the activity on the webwhether it' programmed directly or partly automated by frameworks and tools cgi scripting is perhaps the most primitive approach to implementing websitesand it does not by itself offer the tools that are often built into larger frameworks such as state retentiondatabase interfacesand reply templating cgi scriptshoweverare in many ways the simplest technique for server-side scripting as resultthey are an ideal way to get started with programming on the server side of the web especially for simpler sites that do not require enterprise-level toolscgi is sufficientand it can be augmented with additional libraries as needed the script behind the curtain formally speakingcgi scripts are programs that run on server machine and adhere to the common gateway interface-- model for browser/server communications server-side scripting |
5,693 | use to transfer input data and results between web browsers and other clients and server-side scripts perhaps more useful way to understand cgithoughis in terms of the interaction it implies most people take this interaction for granted when browsing the web and pressing buttons in web pagesbut lot is going on behind the scenes of every transaction on the web from the perspective of userit' fairly familiar and simple processsubmission when you visit website to searchpurchase productor submit information onlineyou generally fill in form in your web browserpress button to submit your informationand begin waiting for reply response assuming all is well with both your internet connection and the computer you are contactingyou eventually get reply in the form of new web page it may be simple acknowledgment ( "thanks for your order"or new form that must be filled out and submitted again andbelieve it or notthat simple model is what makes most of the web hum but internallyit' bit more complex in facta subtle client/server socket-based architecture is at work--your web browser running on your computer is the clientand the computer you contact over the web is the server let' examine the interaction scenario againwith all the gory details that users usually never seesubmission when you fill out form page in web browser and press submission buttonbehind the scenes your web browser sends your information across the internet to the server machine specified as its receiver the server machine is usually remote computer that lives somewhere else in both cyberspace and reality it is named in the url accessed--the internet address string that appears at the top of your browser the target server and file can be named in url you type explicitlybut more typically they are specified in the html that defines the submission page itself--either in hyperlink or in the "actiontag of the input form' html however the server is specifiedthe browser running on your computer ultimately sends your information to the server as bytes over socketusing techniques we saw in the last three on the server machinea program called an http server runs perpetuallylistening on socket for incoming connection requests and data from browsers and other clientsusually on port number processing when your information shows up at the server machinethe http server program notices it first and decides how to handle the request if the requested url names simple web page ( url ending in html)the http server opens the named html file on the server machine and sends its text back to the browser over what' server-side cgi script |
5,694 | next page you see but if the url requested by the browser names an executable program instead ( url ending in cgi or py)the http server starts the named program on the server machine to process the request and redirects the incoming browser data to the spawned program' stdin input streamenvironment variablesand commandline arguments that program started by the server is usually cgi script-- program run on the remote server machine somewhere in cyberspaceusually not on your computer the cgi script is responsible for handling the request from this point onit may store your information in databaseperform searchcharge your credit cardand so on response ultimatelythe cgi script prints htmlalong with few header linesto generate new response page in your browser when cgi script is startedthe http server takes care to connect the script' stdout standard output stream to socket that the browser is listening to as resulthtml code printed by the cgi script is sent over the internetback to your browserto produce new page the html printed back by the cgi script works just as if it had been stored and read from an html fileit can define simple response page or brand-new form coded to collect additional information because it is generated by scriptit may include information dynamically determined per request in other wordscgi scripts are something like callback handlers for requests generated by web browsers that require program to be run dynamically they are automatically run on the server machine in response to actions in browser although cgi scripts ultimately receive and send standard structured messages over socketscgi is more like higher-level procedural convention for sending and receiving information between browser and server writing cgi scripts in python if all of this sounds complicatedrelax--pythonas well as the resident http serverautomates most of the tricky bits cgi scripts are written as fairly autonomous programsand they assume that startup tasks have already been accomplished the http web server programnot the cgi scriptimplements the server side of the http protocol itself moreoverpython' library modules automatically dissect information sent up from the browser and give it to the cgi script in an easily digested form the upshot is that cgi scripts may focus on application details like processing input data and producing result page as mentioned earlierin the context of cgi scriptsthe stdin and stdout streams are automatically tied to sockets connected to the browser in additionthe http server passes some browser information to the cgi script in the form of shell environment variablesand possibly command-line arguments to cgi programmersthat means server-side scripting |
5,695 | stdin input streamalong with shell environment variables output is sent back from the server to the client by simply printing properly formatted html to the stdout output stream the most complex parts of this scheme include parsing all the input information sent up from the browser and formatting information in the reply sent back happilypython' standard library largely automates both tasksinput with the python cgi moduleinput typed into web browser form or appended to url string shows up as values in dictionary-like object in python cgi scripts python parses the data itself and gives us an object with one key value pair per input sent by the browser that is fully independent of transmission style (roughlyby fill-in form or by direct urloutput the cgi module also has tools for automatically escaping strings so that they are legal to use in html ( replacing embedded and characters with html escape codesmodule urllib parse provides additional tools for formatting text inserted into generated url strings ( adding %xx and escapeswe'll study both of these interfaces in detail later in this for nowkeep in mind that although any language can be used to write cgi scriptspython' standard modules and language attributes make it snap perhaps less happilycgi scripts are also intimately tied to the syntax of htmlsince they must generate it to create reply page in factit can be said that python cgi scripts embed htmlwhich is an entirely distinct language in its own right as we'll also seethe fact that cgi scripts create user interface by printing html syntax means that we have to take special care with the text we insert into web page' code ( escaping html operatorsworsecgi scripts require at least cursory knowledge of html formssince that is where the inputs and target script' address are typically specified this book won' teach html in depthif you find yourself puzzled by some of the arcane syntax of the html generated by scripts hereyou should glance at an html introductionsuch as html xhtmlthe definitive guide also keep in mind that higher-level tools and frameworks can sometimes hide the details of html generation from python programmersalbeit at the cost of any new complexity inherent in the interestinglyin we briefly introduced other systems that take the opposite route--embedding python code or calls in html the server-side templating languages in zopepspand other web frameworks use this modelrunning the embedded python code to produce part of reply page because python is embeddedthese systems must run special servers to evaluate the embedded tags because python cgi scripts embed html in python insteadthey can be run as standalone programs directlythough they must be launched by cgi-capable web server what' server-side cgi script |
5,696 | deal in python objectsnot html syntaxthough you must learn this system' api as well running server-side examples like guisweb-based systems are highly interactiveand the best way to get feel for some of these examples is to test-drive them live before we get into some codelet' get set up to run the examples we're going to see running cgi-based programs requires three pieces of softwarethe clientto submit requestsa browser or script the web server that receives the request the cgi scriptwhich is run by the server to process the request we'll be writing cgi scripts as we move alongand any web browser can be used as client ( firefoxsafarichromeor internet exploreras we'll see laterpython' urllib request module can also serve as web client in scripts we write the only missing piece here is the intermediate web server web server options there are variety of approaches to running web servers for examplethe open source apache system provides completeproduction-grade web serverand its mod_python extension discussed later runs python scripts quickly provided you are willing to install and configure itit is complete solutionwhich you can run on machine of your own apache usage is beyond our present scope herethough if you have access to an account on web server machine that runs python xyou can also install the html and script files we'll see there for the second edition of this bookfor instanceall the web examples were uploaded to an account had on the "starshippython serverand were accessed with urls of this formif you go this routereplace starship python net/~lutz with the names of your own server and account directory path the downside of using remote server account is that changing code is more involved--you will have to either work on the server machine itself or transfer code back and forth on changes moreoveryou need access to such server in the first placeand server configuration details can vary widely on the starship machinefor examplepython cgi scripts were required to have cgi filename extensionexecutable permissionand the unix #line at the top to point the shell to python finding server that supports python used by this book' examples might prove stumbling block for some time to come as wellneither of my own isps had it installed server-side scripting |
5,697 | today that do naturallythis may change over time running local web server to keep things simplethis edition is taking different approach all the examples will be run using simple web server coded in python itself moreoverthe web server will be run on the same local machine as the web browser client this wayall you have to do to run the server-side examples is start the web server script and use "localhostas the server name in all the urls you will submit or code (see if you've forgotten why this name means the local machinefor exampleto view web pageuse url of this form in the address field of your web browserthis also avoids some of the complexity of per-server differencesand it makes changing the code simple--it can be edited on the local machine directly for this book' exampleswe'll use the web server in example - this is essentially the same script introduced in augmented slightly to allow the working directory and port number to be passed in as command-line arguments (we'll also run this in the root directory of larger example in the next we won' go into details on all the modules and classes example - uses heresee the python library manual but as described in this script implements an http web serverwhichlistens for incoming socket requests from clients on the machine it is run on and the port number specified in the script or command line (which defaults to that standard http portserves up html pages from the webdir directory specified in the script or command line (which defaults to the directory it is launched fromruns python cgi scripts that are located in the cgi-bin (or htbinsubdirectory of the webdir directorywith py filename extension see for additional background on this web server' operation example - pp \internet\web\webserver py ""implement an http web server in python which knows how to serve html pages and run server-side cgi scripts coded in pythonthis is not production-grade server ( no httpsslow script launch/run on some platforms)but suffices for testingespecially on localhostserves files and scripts from the current working dir and port by defaultunless these options are specified in command-line argumentspython cgi scripts must be stored in webdir\cgi-bin or webdir\htbinmore than one of this server may be running on the same machine to serve from different directoriesas long as they listen on different portsrunning server-side examples |
5,698 | import ossys from http server import httpservercgihttprequesthandler webdir port where your html files and cgi-bin script directory live if len(sys argv webdir sys argv[ if len(sys argv port int(sys argv[ ]print('webdir "% "port % (webdirport)command-line args else default os chdir(webdirrun in html root dir srvraddr (''portmy hostnameportnumber srvrobj httpserver(srvraddrcgihttprequesthandlersrvrobj serve_forever(serve clients till exit to start the server to run this examplessimply run this script from the directory the script' file is located inwith no command-line arguments for instancefrom dos command linec:\pp \internet\webwebserver py webdir "port on windowsyou can simply click its icon and keep the console window openor launch it from dos command prompt on unix it can be run from command line in the backgroundor in its own terminal window some platforms may also require you to have administrator privileges to run servers on reserved portssuch as the web' port if this includes your machineeither run the server with the required permissionsor run on an alternate port number (more on port numbers later in this by defaultwhile running locally this waythe script serves up html pages requested on "localhostfrom the directory it lives in or is launched fromand runs python cgi scripts from the cgi-bin subdirectory located therechange its webdir variable or pass in command-line argument to point it to different directory because of this structurein the examples distribution html files are in the same directory as the web server script and cgi scripts are located in the cgi-bin subdirectory in other wordsto visit web pages and run scriptswe'll be using urls of these formsrespectivelyboth map to the directory that contains the web server script (pp \internet\webby default againto run the examples on different server machine of your ownsimply replace the "localhostand "localhost/cgi-binparts of these addresses with your server name and directory path details (more on urls later in this with this address change the examples work the samebut requests are routed across network to the serverinstead of being routed between programs running on the same local machine the server in example - is by no means production-grade web serverbut it can be used to experiment with this book' examples and is viable as way to test your cgi server-side scripting |
5,699 | server if you wish to install and run the examples under different web serveryou'll want to extrapolate the examples for your context things like server names and pathnames in urlsas well as cgi script filename extensions and other conventionscan vary widelyconsult your server' documentation for more details for this and the nextwe'll assume that you have the webserver py script running locally the server-side examples root page to confirm that you are set up to run the examplesstart the web server script in example - and type the following url in the address field at the top of your web browserthis address loads launcher page with links to this example files (see the examples distribution for this page' html source codewhich is not listed in this bookthe launcher page itself appears as in figure - shown displayed in the internet explorer web browser on windows (it looks similar on other browsers and platformseach major example has link on this pagewhich runs when clicked figure - the pyinternetdemos launcher page running server-side examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.