Python: Modify Values in eml file (email heade

2019-05-18 15:27发布

I would like to have a changes of "To" and "From" field's email addresses using Python. So far now I did following which is working for reading required field. Any one please suggest, How to make change in them.

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条回答
ら.Afraid
2楼-- · 2019-05-18 15:54

You should write the changed message back to the file:

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

Note that your name headers is not completely accurate as the value returned by email.parser.Parser.parse is email.message.Message.

查看更多
登录 后发表回答