python3下载邮件附件

python3下载.eml文件的附件

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

  • python3(pip install 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", 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)

    原文作者:xkw168
    原文地址: https://blog.csdn.net/kewei168/article/details/84574594
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞