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

Tig*_*gre 4 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();
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我一直得不到答案,有什么帮助吗?

小智 6

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

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
Run Code Online (Sandbox Code Playgroud)