【问题标题】:Unable to download all documents from eml file无法从 eml 文件下载所有文档
【发布时间】:2020-03-10 20:22:21
【问题描述】:

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

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 仍然没有下载所有文件。

【问题讨论】:

  • eml_file 未初始化
  • 感谢您的指出。我现在已经完成了,但仍然只下载 1 个文件。

标签: python email-attachments eml


【解决方案1】:

您导入了email 模块。那么为什么你忽略它并尝试自己编写一个电子邮件解析器呢?另外:

  1. 您可以使用glob 列出具有给定扩展名的所有文件。
  2. 使用应该在条件:(if not os.path.exists("output"): os.makedirs("output")) 中使用not 运算符,但即使这样也没有必要,因为makedirsexist_ok 参数。
import os
import glob
import email
from email import policy

indir = '.'
outdir = os.path.join(indir, 'output')

os.makedirs(outdir, exist_ok=True)
files = glob.glob(os.path.join(indir, '*.eml'))

for eml_file in files:
    # This will not work in Python 2
    msg = email.message_from_file(open(eml_file), policy=policy.default)
    for att in msg.iter_attachments():
        # Tabs may be added for indentation and not stripped automatically
        filename = att.get_filename().replace('\t', '')
        # Here we suppose for simplicity sake that each attachment has a valid unique filename,
        # which, generally speaking, is not true.
        with open(os.path.join(outdir, filename), 'wb') as f:
            f.write(att.get_content())

【讨论】:

  • 非常感谢。我明白我做错了什么。一个问题。哪个是无需下载即可从电子邮件附件中提取数据的最佳软件包?
  • 不客气。如果您的意思是从电子邮件服务器获取附件而不先将邮件保存为 .eml,则很可能您需要使用imaplib 模块,如下所述:pymotw.com/2/imaplib
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多