如何使用Python从电子邮件内容中获取附件的eml文件?

问题描述 投票:2回答:1

我正在使用python 3.7和电子邮件,imap库读取电子邮件并提取电子邮件和附件的内容,所有附件(如excel,csv,pdf)都作为附件下载,但是当我在电子邮件中收到任何.eml文件时,它向我显示错误,请找到以下代码以阅读电子邮件内容和附件,并显示错误消息(如果接收到eml文件作为附件,则显示错误)。写入eml文件时显示错误。在写入时。在eml文件中,get_payload(decode = True)为空白。

filename = part.get_filename()
if filename is not None:
    dot_position = filename.find('.')
    file_prefix = filename[0:dot_position]
    file_suffix = filename[dot_position:len(filename)]
    # print(dot_position)
    # print(file_prefix)
    # print(file_suffix)
    now = datetime.datetime.now()
    timestamp = str(now.strftime("%Y%m%d%H%M%S%f"))
    newFileName = file_prefix + "_" + timestamp + file_suffix
    sv_path = os.path.join(svdir, newFileName)
    # allfiles = allfiles.append([{"oldfilename": filename, "newfilename": newFileName}])
    mydict = filename + '$$' + newFileName
    mydict1 = mydict1 + ',' + mydict
    print(mydict1)
    if not os.path.isfile(sv_path):
        print("oldpath:---->" + sv_path)
        # filename = os.rename(filename, filename + '_Rahul')
        # sv_path = os.path.join(svdir, filename)
        # print("Newpath:---->" + sv_path)
        fp = open(sv_path, 'wb')
        # print("Rahul")
        print(part.get_payload(decode=True))
        # try:
        # newFileByteArray = bytearray(fp)
        # if part.get_payload(decode=True) is not None:
        fp.write(part.get_payload(decode=True))
        # except (TypeError, IOError):
        #    pass
        fp.close()

错误是

<class 'TypeError'> ReadEmailUsingIMAP.py 129
a bytes-like object is required, not 'NoneType'
python python-3.x python-3.7 imaplib
1个回答
0
投票

使用eml_parserhttps://pypi.org/project/eml-parser/导入日期时间导入json导入eml_parser

def json_serial(obj):
    if isinstance(obj, datetime.datetime):
        serial = obj.isoformat()
        return serial


with open('sample.eml', 'rb') as fhdl:
    raw_email = fhdl.read()

parsed_eml = eml_parser.eml_parser.decode_email_b(raw_email)

print(json.dumps(parsed_eml, default=json_serial))
© www.soinside.com 2019 - 2024. All rights reserved.