2015-10-20 110 views

回答

3

這是可能的,容易。我們假設msg是以前編寫的包含所有標題和內容的消息,並且您要將其寫入文件對象out。你只需要:

gen = email.generator.Generator(out) # create a generator 
gen.flatten(msg) # write the message to the file object 

完整的示例:

import email 

# create a simple message 
msg = email.mime.text.MIMEText('''This is a simple message. 
And a very simple one.''') 
msg['Subject'] = 'Simple message' 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 

# open a file and save mail to it 
with open('filename.elm', 'w') as out: 
    gen = email.generator.Generator(out) 
    gen.flatten(msg) 

filename.elm的內容是:

Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 
Subject: Simple message 
From: [email protected] 
To: [email protected] 

This is a simple message. 
And a very simple one. 
+0

謝謝。我從我的'emails'實例創建了一個'email'實例,它工作正常,但是有沒有辦法將它保存爲'msg'而不是'eml'?我試圖用open('filename.elm','w')'將'open'('filename.msg','w')'改成''但是(如預期的)outlook無法打開該文件。 – DeepSpace

+0

@DeepSpace msg格式是一種二進制專有格式。使用它的唯一合理方式是通過展望自動化。在SO中搜索'[python] outlook msg file'給了[這個問題](http://stackoverflow.com/q/18066180/),可以給你一些提示。我無法進一步幫助你,因爲我幾十年來一直沒有使用outlook。 –

-1

它是在Python可行的,我想下面的代碼,節省展望郵件作爲.msg文件夾中。 注意:確保outlook具有對目標文件夾的寫入權限,默認情況下目標文件夾是Python腳本的位置

import win32.com 

outlook=Dispatch("Outlook.Application").GetNamespace("MAPI") 
inbox=outlook.GetDefaultFolder(6) 
messages=inbox.items 
for msg in messages: 
    name=msg.subject 
    name=str(name) 
    name=name+".msg" 
    msg.saveas(name) 
相關問題