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

3
我希望使用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个回答

2
你应该将更改的消息写回到文件中:
with open('2.eml', 'w') as outfile:
    outfile.write(headers.as_string())

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接