Python:修改eml文件中的值(电子邮件标题)

时间:2016-05-31 10:39:02

标签: python parsing eml

我想更改" To"和"来自"使用Python的字段的电子邮件地址。到目前为止,我做了以下工作,正在阅读所需的字段。请任何人建议,如何改变它们。

from email.parser import Parser

fp = open('2.eml', 'r+')
headers = Parser().parse(fp)

# Make changes only within a code, Not in to the file. I would like to save given changes for from in to my 2.eml file
headers.replace_header('from', 'newEmail@domain.com') 

print ('To: %s' % headers['to'])
print ('From: %s' % headers['from'])
print ('Subject: %s' % headers['subject'])

1 个答案:

答案 0 :(得分:1)

您应该将更改后的消息写回文件:

with open('2.eml', 'w') as outfile:
    outfile.write(headers.as_string())

请注意,您的姓名headers并不完全准确,因为email.parser.Parser.parse返回的值为email.message.Message

相关问题