標籤:end ocs 下載 ber close http join cte write
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, email10 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 mailbox23 print(" %d mails." % len(maillist))24 dellist = []25 26 for item in maillist: # email download27 number, octets = item.split(‘ ‘)28 print("Start downloading mail %s (%S Bytes)" % (number, octets))29 lines = P.retr(number)[1] # retrieve the ‘number‘th email30 msg = email.message_from_string("\n".join(lines)) # email object31 with open(storedir) as FH:32 FH.write(msg.as_string(unixfrom=1) + "\n")33 dellist.append(number)34 print("Downloaded mail %s (%S Bytes)" % (number, octets))35 36 counter = 037 for num in dellist: # delete email38 counter += 139 print("Deleting mail %d of %d" %(counter, len(dellist)))40 P.dele(number) # delete mail41 42 print("%d emails were deleted from server" % counter)43 P.quit() # logout from server44 45 IMAP - Internet Message Access Protocol46 相比於 POP 協議 IMAP 更加完善,且功能更加強大47 例子, opens a mailbox and retrieves and prints all messages:48 49 import getpass, imaplib50 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\n%s\n‘ % (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
POP and IMAP - Post Office Protocol and Internet Message Access Protocol