jaymin581
jaymin581

Reputation: 165

Python: Modify Values in eml file (email header)

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', '[email protected]') 

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

Upvotes: 3

Views: 1864

Answers (1)

Jieter
Jieter

Reputation: 4229

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.

Upvotes: 2

Related Questions