从Python中的电子邮件附件中获取文件名

时间:2011-06-21 17:26:36

标签: python email attachment

我使用我的凭据登录到服务器,然后搜索包含特定主题的电子邮件。这个特定的电子邮件有一个附件,我想知道它的文件名,以及稍后可能的扩展名。

我在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();

我不知道为什么我一直没有得到任何帮助?

4 个答案:

答案 0 :(得分:1)

如果您将所有内容转储到“part”中,您实际上是否在那里看到了文件?

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我遇到了同样的问题,这就是我要解决的问题:

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

答案 3 :(得分:0)

您需要先检查

for part in msg.walk():

    print (part.get_content_type())

然后在主要for循环中 -

for part in msg.walk():

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

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

ex -I遇到了同样的问题,我的内容类型是 multipart text / html application / 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 

` 不会有错误。

我希望它有所帮助