python批量下載郵件附件


背景

由於同學每周要通過郵箱收數學建模作業,100多人給她發附件,她要一個個地點着下載。

太麻煩了,所以想用程序實現下載附件的功能。

在網上查資料后,最終實現了稍為簡單的下載附件功能,代碼有些細節還不是很了解。

2019.4.16更新

過幾天我也要用郵箱收文件,有了這份代碼剛好能用!這再次印證知識不會沒用處的,不學才會覺得知識沒用呢。

代碼

import poplib
import email
import time
from email.parser import Parser
from email.header import decode_header


def decode_str(s):#字符編碼轉換
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value


def get_att(msg):
    attachment_files = []

    for part in msg.walk():
        file_name = part.get_filename()  # 獲取附件名稱類型
        contType = part.get_content_type()

        if file_name:
            h = email.header.Header(file_name)
            dh = email.header.decode_header(h)  # 對附件名稱進行解碼
            filename = dh[0][0]
            if dh[0][1]:
                filename = decode_str(str(filename, dh[0][1]))  # 將附件名稱可讀化
                print(filename)
                # filename = filename.encode("utf-8")
            data = part.get_payload(decode=True)  # 下載附件
            att_file = open('D:\\數模作業\\' + filename, 'wb')  # 在指定目錄下創建文件,注意二進制文件需要用wb模式打開
            attachment_files.append(filename)
            att_file.write(data)  # 保存附件
            att_file.close()
    return attachment_files



with open('D:\\config.txt', 'r') as f1:
    config = f1.readlines()
for i in range(0, len(config)):
    config[i] = config[i].rstrip('\n')

# print(config)

# POP3服務器、用戶名、密碼
host = config[0]  # pop.163.com
username = config[1]  # 用戶名 
password = config[2]  # 密碼

# 連接到POP3服務器
server = poplib.POP3(host)

# 身份驗證
server.user(username)
server.pass_(password)

# stat()返回郵件數量和占用空間:
# print('Messages: %s. Size: %s' % server.stat())

# 可以查看返回的列表類似[b'1 82923', b'2 2184', ...]
resp, mails, octets = server.list()
# print(mails)

# 倒序遍歷郵件
index = len(mails)
for i in range(index, 0, -1):
    # lines存儲了郵件的原始文本的每一行
    resp, lines, octets = server.retr(i)

    # 郵件的原始文本:
    msg_content = b'\r\n'.join(lines).decode('utf-8')

    # 解析郵件:
    msg = Parser().parsestr(msg_content)

    # 獲取附件
    f_list = get_att(msg)

print("文件已下載完成,10秒后關閉程序!")
time.sleep(10)

打包

使用pyinstaller,將該.py文件打包成.exe文件。

pyinstaller -F xuer.py

這樣她就不需要安裝python,方便她使用。

為了保護她的密碼隱私,程序通過她自己的文件獲得她的用戶名和密碼,之后文件會自動下載到D盤中數學建模文件夾下。

作者:@臭咸魚

本文為作者原創,轉載請注明出處:https://chouxianyu.github.io

歡迎討論和交流!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM