3

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'])
jaymin581
  • 165
  • 3
  • 15

1 Answers1

2

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.

Jieter
  • 4,101
  • 1
  • 19
  • 31