"Python3" POP3 agreement to receive mail

Source: Internet
Author: User

Beginner Python3, do an email example, although know to do very slag, or share it

POP3 protocol

POP3 Full name Post official Protocol3, the third version of the Post Office Protocol, provides a mail server for connecting personal computers to the Internet and an electronic protocol for downloading e-mail, which is the first offline standard for Internet electronic protocols, POP3 allows users to store messages from the server to a local host (personal computer) while deleting messages saved on the mail server, while the POP3 server is a mail server that follows the POP3 protocol to receive e-mail.

Python3 Support POP3 module is poplib: Establish a connection (to initialize the POP3), username/password authentication, get mail information/download mail/delete mail processing, exit and update processing.

POP3 protocol model and processing is very intuitive, get to the message after the parsing message is major problem!

The code is as follows

ImportPoplib
ImportSys
fromImportlibImportReload
fromEmail.parserImportParser
fromEmail.parserImportBytesparser
fromEmail.headerImportDecode_header
fromEmail.utilsImportParseaddr
ImportEmail.iterators

#parse a string in a message header
defDECODE_STR (s):
Value, CharSet = Decode_header (s) [0]
ifCharSet
Value = Value.decode (CharSet)
returnValue

#save a message attachment or content to a file
#the attachment data in the message is written to the attachment file
defSaveFile (filename, data, path):
Try:
filepath = path + filename
Print('Save as:'+ filepath)
f = open (filepath,'WB')
except:
Print(filepath +'Open Failed')
#f.close ()
Else:
F.write (data)
F.close ()

#gets the character encoding of the message, first looking for the encoding in the message, if not, looking in the header's Content-type
defGuess_charset (msg):
CharSet = Msg.get_charset ()
ifCharSet isNone:
Content_Type = Msg.get ('Content-type',"'). Lower ()
pos = Content_type.find ('charset=')
ifPOS >= 0:
CharSet = Content_type[pos+8:].strip ()
returnCharSet

#functions that parse the message, first print the recipient, sender, title
#The walk of the message is then called to loop through each sub-object (including text, HTML, attachments one or more times) in the messages
#The filename in the message header attribute is present, the child object is an attachment, the attachment name is encoded and the attachment is downloaded to the specified directory
#since messages transmitted over the network are encoded in a later format, you need to specify decode=true at Get_payload to convert to an output encoding
#if the message is in text or HTML format, print the format and output the sub-object content after transcoding
defPrint_info (msg):
forHeaderinch[' from',' to','Subject']:
Value = Msg.get (header,"')
ifValue
ifHeader = ='Subject':
Value = Decode_str (value)
Else:
HDR, addr = parseaddr (value)
Name = Decode_str (addr)
Value = name +'<'+ addr +'>'
Print(Header +':'+ value)
forPartinchMsg.walk ():
filename = Part.get_filename ()
Content_Type = Part.get_content_type ()
CharSet = Guess_charset (part)
ifFileName
filename = decode_str (filename)
data = part.get_payload (decode = True)
ifFileName! = NoneorFileName! ="':
Print('Accessory:'+ filename)
SaveFile (filename, data, mypath)
Else:
Email_content_type ="'
Content ="'
ifContent_Type = ='Text/plain':
Email_content_type ='text'
elifContent_Type = ='text/html':
Email_content_type ='HTML'
ifCharSet
Content = Part.get_payload (decode=true). Decode (CharSet)
Print(Email_content_type +' '+ content)

email ='[email protected]'
Password ='email_passwd'
Pop3_server ='pop.163.com'
MyPath ='d://email/'

Server = Poplib. POP3 (Pop3_server, 110)
#print (Server.getwelcome ())
Server.user (email)
Server.pass_ (password)
Print('Message:%s. Size:%s'% Server.stat ())

RESP, mails, objects = Server.list ()
#print (mails)
index = len (mails)
#Take out all the information of a single message
RESP, lines, octets = SERVER.RETR (index)
#message is bytes, converted to parser supported STR
Lists = []
forEinchLines
Lists.append (E.decode ())
Msg_content ='\ r \ n'. Join (Lists)
msg = Parser (). PARSESTR (Msg_content)
Print_info (msg)
#Server.dele (Index)
#submit operation information and exit
Server.quit ()

"Python3" POP3 agreement to receive mail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.