POP and IMAP

 1 POP and IMAP - Post Office Protocol and Internet Message Access Protocol
 2 
 3 用来从 SMTP Server 上下载邮件的协议.
 4 
 5     POP - The Post Office Protocol
 6         通过 poplib 链接服务器,
 7         例子,
 8             import sys
 9             import poplib, email
10             host = ''
11             userid = 'userid'
12             PW = 'PW'
13             storedir = '' # email stored directory(the mailbox)
14             P = poplib.POP3(host)
15             try:
16                 P.user(userid)
17                 P.pass_(PW)
18             except poplib.error_proto as e:
19                 print("Login failed: ", e)
20                 sys.exit()
21 
22             maillist = P.list()[1]   # the list of message in the mailbox
23             print(" %d mails." % len(maillist))
24             dellist = []
25 
26             for item in maillist:   # email download
27                 number, octets = item.split(' ')
28                 print("Start downloading mail %s (%S Bytes)" % (number, octets))
29                 lines = P.retr(number)[1]  # retrieve the 'number'th email
30                 msg = email.message_from_string("
".join(lines)) #  email object
31                 with open(storedir) as FH:
32                     FH.write(msg.as_string(unixfrom=1) + "
")
33                 dellist.append(number)
34                 print("Downloaded mail %s (%S Bytes)" % (number, octets))
35 
36             counter = 0
37             for num in dellist:   # delete email
38                 counter += 1
39                 print("Deleting mail %d of %d" %(counter, len(dellist)))
40                 P.dele(number) # delete mail
41 
42             print("%d emails were deleted from server" % counter)
43             P.quit() # logout from server
44 
45     IMAP - Internet Message Access Protocol
46         相比于 POP 协议  IMAP 更加完善,且功能更加强大
47         例子, opens a mailbox and retrieves and prints all messages:
48 
49             import getpass, imaplib
50             M = imaplib.IMAP4()
51             M.login(getpass.getuser(), getpass.getpass())
52             M.select()
53             typ, data = M.search(None, 'ALL')
54             for num in data[0].split():
55                 typ, data = M.fetch(num, '(RFC822)')
56                 print('Message %s
%s
' % (num, data[0][1]))
57             M.close()
58             M.logout()
59 
60 Reference,
61     python doc,
62         https://docs.python.org/3/library/imaplib.html
原文地址:https://www.cnblogs.com/zzyzz/p/8134814.html