Python從郵箱下載附件

需求說(shuō)明

如果你收作業(yè)的方式仍然是通過(guò)QQ發(fā)送給你,或者郵箱,在一個(gè)一個(gè)點(diǎn)擊下載下來(lái)的話(huà),那么這個(gè)小程序特別適合你,能幫你減輕工作量。

使用說(shuō)明

首先發(fā)件人的郵件標(biāo)題要按照一定的規(guī)則或者前綴,這樣才知道要下載哪個(gè)附件。比如$計(jì)算機(jī)網(wǎng)絡(luò)實(shí)驗(yàn)4$
填好郵箱賬號(hào)密碼,輸入前綴,就自動(dòng)下載了。

代碼如下:

#!/usr/bin/env python3
# coding=utf-8

import poplib  
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr 

def decode_str(s):
    if not s:
        return None
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value

def get_mails(prefix):
    host = 'pop.163.com'  
    username = '賬號(hào)'  
    password = '密碼'  
      
    server = poplib.POP3(host)
    server.user(username)
    server.pass_(password)
    # 獲得郵件
    messages = [server.retr(i) for i in range(1, len(server.list()[1]) + 1)]  
    messages = [b'\r\n'.join(mssg[1]).decode() for mssg in messages]  
    messages = [Parser().parsestr(mssg) for mssg in messages]  
    print("===="*10)
    messages = messages[::-1]
    for message in messages:  
        subject = message.get('Subject')
        subject = decode_str(subject)
        #如果標(biāo)題匹配
        if subject and subject[:len(prefix)] == prefix:
            value = message.get('From')
            if value:
                hdr, addr = parseaddr(value)
                name = decode_str(hdr)
                value = u'%s <%s>' % (name, addr)
            print("發(fā)件人: %s" % value)
            print("標(biāo)題:%s" % subject)
            for part in message.walk():  
                fileName = part.get_filename()  
                fileName = decode_str(fileName)
                # 保存附件  
                if fileName:  
                    with open(fileName, 'wb') as fEx:
                        data = part.get_payload(decode=True) 
                        fEx.write(data)  
                        print("附件%s已保存" % fileName)
    server.quit()  

if __name__ == '__main__':
    prefix = input("輸入要下載的郵件標(biāo)題的前綴:")
    get_mails(prefix)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容