最近经常干的一件事就是面对几十个的.eml文件,逐个打开并下载附件,今天突发奇想,人生苦短,快用python,那么为啥这种重复性的工作不用python替代呢,说干就干 环境配置

关键函数:

def download_attachment(mailname, datapath):
    """
    download the attachment of .eml file
    :param mailname: path of .eml path
    :param datapath: path of the attachment file
    :return: None
    """
    fp = open(mailname, "r", encoding='gbk')
    msg = email.message_from_file(fp)

    for par in msg.walk():
        if not par.is_multipart():
            name = par.get_param("name")

            if name:
                h = email.header.Header(name)

                data = par.get_payload(decode=True)

                data_name = str(h).replace('/', '_')
                f = open(datapath + '\\' + data_name, 'wb')
                f.write(data)
                f.close()

完整代码(下载整个文件夹里面所有.eml文件的附件):

#!/usr/bin/env python3

import os
import email


def download_attachment(mailname, datapath):
    """
    download the attachment of .eml file
    :param mailname: path of .eml path
    :param datapath: path of the attachment file
    :return: None
    """
    fp = open(mailname, "r")
    msg = email.message_from_file(fp)

    for par in msg.walk():
        if not par.is_multipart():
            name = par.get_param("name")

            if name:
                h = email.header.Header(name)

                data = par.get_payload(decode=True)

                data_name = str(h).replace('/', '_')
                f = open(datapath + '\\' + data_name, 'wb')
                f.write(data)
                f.close()


if __name__ == '__main__':
    dir = "C:\\Users\\xkw\\Desktop\\srcData\\"
    datapath = "C:\\Users\\xkw\\Desktop\\destData"
    count = 0

    for filename in os.listdir(dir):
        filename = dir + filename
        print(filename)
        download_attachment(filename, datapath)