Python operation e-mail, not very convenient, to tell the truth is not particularly thorough understanding, this time I want to sum up the things I encountered
E-Mail has a IMAP,POP,IMAP protocol, this time using the IMAP4 protocol, mainly used IMAP4 and mail class,
The code mainly refers to the http://blog.csdn.net/bonnshore/article/details/8729984, which is written in very detailed, can be implemented to send and receive mail
Here is the main code to paste:
Initialize, define mail server
Self. imap_server='imap.gmail.com'self . Imap_port=993 = None self.response
Login, select mailbox:
Self. M ==
Mail search:
' BODY ', DataPath)
Get message information:
Status, Response = self. M.fetch (ID,"(RFC822)") Mailtext= Response[0][1]mail_message=email.message_from_string (mailtext) Subject= Unicode (email. Header.make_header (email. Header.decode_header (mail_message['subject'])))#print "subject_________:" +subjectMail_from = Email.utils.parseaddr (mail_message[" from"]) [1]mail_to= Email.utils.parseaddr (mail_message[" to"]) [1]time= mail_message['Date']Print '['+mail_message['Date']+']'+'\ n'+'From :'+mail_from+'To :'+mail_to+'\ n'+'Subject:'+subject+'\ n'returnSelf.get_first_text_block (mail_message), subject, Mail_from, time
MainType = Email_message_instance.get_content_maintype () returns the type of content in the message, if the text is better to handle, if it is multipart, you have to traverse Email_ Message_instance to deal with different types.
Email.message_from_string (mailtext) returns a struct that contains the basic information of the message
E-mail comparison of the egg is the problem of string encoding, after all, the message format is not the same, some are Unicode, some are utf-8, some are gb2312, there are attachments, pictures and other formats,
Of course, this time only processed the text, there is no need to deal with attachments and pictures of these. I'm all unified. Convert characters to Unicode to handle.
String processing, you can use Chardet to determine the string type, read and write files can be used to specify read and write character set type codecs
Also affixed to the worthy reference of Python processing of mail articles;
Http://www.programcreek.com/python/example/58598/email.message.as_string (some examples of handling mail)
https://tools.ietf.org/html/rfc3501#section-6.4.4 (reference for mail search)
Python Mail Basics