來看看怎麼使用吧:
d = self.proto.login(self.factory.username, self.factory.password)
d.addCallback(lambda x: self.proto.examine('INBOX'))
d.addCallback(lambda x: self.proto.fetchSpecific('1:*', peek = 1))
d.addCallback(self.gotmessages)
d.addCallback(self.logout)
d.addCallback(self.stopreactor)
可以看到使用protocol class的fetchSpecific()就可以抓取信件。而第一個參數'1:*'則表示抓取的範圍是從第1封到最後一封,也就是所有的信件;第二個參數把peek設定為1,是要server不要在我們把信抓下來後就加上/seen已讀的flag(預設是會加的)。
再來就是看看gotmessages如何處理信件:
def gotmessages(self, data):
destfd = open(sys.argv[3], 'at')
for key, value in data.items():
print "Writing message", key
msg = email.message_from_string(value[0][2])
destfd.write(msg.as_string(unixfrom = 1))
destfd.write("\n")
destfd.close()
fetchSpecific傳給data,data會是dictionary。key是message number,而value就是components of the list。我們把value中[0][2]是代表entire message直接寫入目標檔案中,就算完成囉!
來看output:
cacaegg@cacabook:~/workspace/NetworkProgram/src/IMAP$ tdlbig.py mx.mgt.ncu.edu.tw cacaegg mailbox
Enter password:
Writing message 1
Writing message 2
Writing message 3
程式連結
沒有留言:
張貼留言