我試圖從.msg文件中提取附件。 github上的解決方案太詳細了,我不能正確理解,這裏的答案並不盡如人意。在另一個類似於我的問題中指出了這個example,但我一直無法弄清楚這個函數是如何工作的。
我相信我接近,但無法弄清楚它是什麼我768,16與開幕 - 開放(msgFile)爲FP:這是我到目前爲止的代碼:19.1.14電子郵件:示例 - 第5個示例的問題
import os
import sys
import email
import errno
import mimetypes
from argparse import ArgumentParser
def main():
parser = ArgumentParser(description = """\
Unpack a MIME message into a directory of files.
""")
parser.add_argument('-d', '-- C:\\Users\\MikeS\\Documents\\ImproveBKFS\\Python\\msg_extract', required = True,
help = """Unpack the MIME message into the named
directory, which will be created if it doesn't already
exist.""")
parser.add_argument('TestFile.msg')
args = parser.parse_args()
with open(args, 'wb') as fp: #issues with open(args)
msg = email.message_from_file(fp)
try:
os.mkdir(args.directory)
except FileExistsError:
pass
counter = 1
for part in msg.walk():
#multipar/* 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()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
#Use a generic bag-of-bit extension
ext = '.bin'
filename = 'part-%03d%' % (counter, ext)
counter +=1
with open(os.path.join(arg.directory, filename), 'wb') as fp:
fp.write(part.get_payload(decode=True))
if __name__ == '__main__':
main()
我被困第20行這裏是我的輸入和錯誤消息。
PS C:\Users\MikeS\Documents\\Python\msg_extract> py -3 get_payload_3.py -d ^V TestFile.msg
Namespace(C:\Users\MikeS\Documents\Python\msg_extract='\x16', TestFile.msg='TestFile.msg')
Traceback (most recent call last):
File "get_payload_3.py", line 53, in <module>
main()
File "get_payload_3.py", line 26, in main
with open(args) as fp: #something with this line
TypeError: invalid file: Namespace(C:\Users\MikeS\Documents\Python\msg_extract='\x16', TestFile.msg='Test
File.msg')
任何輸入或輸入類型的線索我需要給這個函數將是一個巨大的幫助。謝謝
謝謝你,我看了一下python.org的argparse文檔,但是在這個例子中如何使用它仍然有點困惑,但是你破解代碼幫助我更充分地消化它。 – Mwspencer