我使用憑證登錄到服務器,然後搜索具有特定主題的電子郵件。這封電子郵件有一個附件,我想知道它的文件名,並可能在稍後擴展。從Python中的電子郵件附件獲取文件名
我在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作爲答案,有什麼幫助嗎?
我在DOS菜單中看到文件時 - 打印(部分);如果這就是你的意思,我是python的初學者,昨天拿起它。我也在我保存這個python腳本的地方得到這個KSH文件,如果這與它有任何關係。 – Tigre
好的,如果你能在那裏看到它,那麼你可能沒有正確的方式訪問它。 –
我將如何訪問它,我已經嘗試過get_filename(),但即使get_content_type()返回text/plain是正確的,但它不返回任何內容..感謝迄今爲止,雖然對於協助 – Tigre