【问题标题】:Get Filename from email attachment in Python从 Python 中的电子邮件附件中获取文件名
【发布时间】:2011-09-19 17:46:18
【问题描述】:

我正在使用我的凭据登录服务器,并搜索具有特定主题的电子邮件。这封电子邮件有一个附件,我想知道它的文件名和可能的扩展名。

我在 Python 中执行此操作,但每次询问文件名时,它都会返回 NONE,而实际上附件中有一个文件名。

from imaplib import *
import base64
import email
import os
import sys
import errno
import mimetypes




server = IMAP4("SERVER LOCATION");

server.login("USER", "PASS");
server.select("Inbox");

typ, data = server.search(None, '(SUBJECT "Hello World")');

for num in data[0].split():
    typ, data = server.fetch(num, '(RFC822)');
    print (data);
    msg = email.message_from_string(str(data[0][1]));

      counter = 1
for part in msg.walk():
    print (part.as_string() + "\n")
    # multipart/* are just containers
    if part.get_content_maintype() == 'multipart':
        continue
    # Applications should really sanitize the given filename so that an
    # email message can't be used to overwrite important files
    filename = part.get_filename()


    print (filename);

    fn = msg.get_filename()

    print("The Filename was:", (fn));


    if not filename:
        ext = mimetypes.guess_extension(part.get_content_type())


                        if not ext:
            # Use a generic bag-of-bits extension
            ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
    counter += 1


server.close()


server.logout();

我不知道为什么我总是得到 NONE 作为答案,有什么帮助吗?

【问题讨论】:

    标签: python email attachment


    【解决方案1】:

    如果您将所有内容都转储到“部分”中,您真的会在那里看到文件吗?

    【讨论】:

    • 当我这样做时,我在 DOS 菜单中看到了该文件 -- print(part);如果这就是你所说的转储,我是python的初学者,昨天拿起它。如果与此有关,我还会在保存此 python 脚本的位置获取此 KSH 文件。
    • 好的,如果您可以在其中看到它,那么您可能没有以正确的方式访问它。
    • 我将如何访问它,我已经尝试过 get_filename() 但它没有返回任何内容,即使 get_content_type() 返回的 text/plain 是正确的.. 感谢到目前为止的帮助
    • 我猜你正在使用这里的代码:docs.python.org/library/email-examples.html 看起来你还有一些行要添加。查看以“如果不是文件名:”开头的位,我认为这与您在测试中遇到的问题有关。不是吗?
    • 是的,我正在使用 python 文档中的代码。我以为你提到我的部分将用于上传/发送电子邮件,但我明天进去时会尝试一下。非常感谢您的帮助。
    【解决方案2】:

    我也遇到了类似的问题。只需删除 如果 part.get_content_maintype() == 'multipart': 继续 条件,它会正常工作。

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,这是我解决它的方法:

      if msg.get_content_maintype() == 'multipart': #multipart messages only
          # loop on the parts of the mail
          for part in msg.walk():
          #find the attachment part - so skip all the other parts
              if part.get_content_maintype() == 'multipart': continue
              if part.get_content_maintype() == 'text': continue
              if part.get('Content-Disposition') == 'inline': continue
              if part.get('Content-Disposition') is None: continue
      
      
              #save the attachment in the program directory
              print "part:", part.as_string()
              filename = part.get_filename()
              print "filename :", filename
                              filepath=DIR_SBD+filename
              fp = open(filepath, 'wb')
              fp.write(part.get_payload(decode=True))
              fp.close()
              print '%s saved!' % filepath
      

      【讨论】:

        【解决方案4】:

        你需要先检查

        for part in msg.walk():
        
            print (part.get_content_type())
        

        然后在主for循环中-

        for part in msg.walk():
        

        只针对邮件正文中存在但您不需要的内容类型继续。

        您也可以直接检查所需的 content_type,然后读取文件名。

        ex - 我遇到了同样的问题,我的内容类型是 multiparttext/htmlapplication/json

        我没有检查 text/html,而是想阅读“application/json”中的附件。我直接读取文件名,因此出现错误 - 文件名无。

        当我把支票—— `

        if part.get_content_maintype() == 'text/html':
            continue
        
        if part.get('Content-Type')== 'application/json':
        
            filename = part.get_filename().split('.')
        
        #do the stuff needed 
        

        ` 不会出现错误。

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 2011-08-20
          • 1970-01-01
          • 2020-11-06
          • 1970-01-01
          • 2016-11-01
          • 2015-05-28
          • 2013-04-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多