无法从eml文件下载所有文档

时间:2019-11-14 19:12:34

标签: python email-attachments eml

我有一个带有3个附件的.eml文件。我能够下载其中一个附件,但无法下载所有附件。

import os
import email
import base64
# Get list of all files
files = [f for f in os.listdir('.') if os.path.isfile(f)]
# Create output directory
if os.path.exists("output"):
    pass
else:
    os.makedirs("output")

for eml_file in files:
    if eml_file.endswith(".eml"):
        with open(eml_file) as f:
            email = f.read()

        ext=".docx"

        if ext is not "":
            # Extract the base64 encoding part of the eml file
            encoding = email.split(ext+'"')[-1]
            if encoding:
                # Remove all whitespaces
                encoding = "".join(encoding.strip().split())
                encoding = encoding.split("=", 1)[0]
                # Convert base64 to string
                if len(encoding) % 4 != 0: #check if multiple of 4
                   while len(encoding) % 4 != 0:
                       encoding = encoding + "="
                try:
                    decoded = base64.b64decode(encoding)
                except:
                    print(encoding)
                    for i in range(100):
                        print('\n')
                # Save it as docx
                path = os.path.splitext(eml_file)[0]
                if path:
                    path = os.path.join("output", path + ext)
                    try:
                        os.remove(path)
                    except OSError:
                        pass
                    with open(path, "wb") as f:
                        f.write(decoded)
        else:
            print("File not done: " + eml_file)

如何下​​载所有附件? 编辑:我已经初始化eml_file仍然不下载所有文件。

1 个答案:

答案 0 :(得分:1)

您导入,Item Description,,On Order,,BackOrd Qty,,On-hand Qty,,Item Name,,Vendor Name,,Active Price,,Item #,,Cost,,Avail Qty,,Department,,Attribute,,Size,,Margin %,,Ext Cost,,Ext Price,,Item Type,,Unit of Measure,,UPC,,Alternate Lookup,,Last Rcvd,,Reorder Point,,Regular Price,,Order Cost,,Margin,,Sale,,Wholesale,,MSRP,,1 Qty,,Custom price,,Dept Code,,Vendor Code,,Cust Ord Qty,,BackOrd Cost,,Last Sold,,Picture Assigned,,Manufacturer,,Shipping Weight,,Length,,Width,,Height,,Eligible for Rewards,,Creation Date,,Quick Pick Group,,Mobile,, ,Booster Pack ,,0,,0,,796,,83717845997,,,,1.99,,2977,,1.09,,796,,Financial Software,,,,,,45.1,,869.65,,"1,584.04",,Inventory,,,,0083733997,,08371734000,,9/26/2019,,0,,1.99,,1.07,,0.9,,1.79,,1.79,,0,,796,,1.79,,,,,,0,,0,,10/19/2019,,FALSE,,,,0,,0,,0,,0,,TRUE,,9/25/2019,,,,FALSE,, 模块。那么,为什么要忽略它并尝试自己编写电子邮件解析器呢?另外:

  1. 您可以使用email列出具有给定扩展名的所有文件。
  2. 使用情况下,应该使用glob运算符:(not),但由于if not os.path.exists("output"): os.makedirs("output")的参数为makedirs,因此甚至没有必要。
exist_ok
相关问题