I am attempting to write a pretty printed email to a .txt file so i can better view what I want to parse out of it.
Here is this section of my code:
result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')
f = open("da_email.txt", "w")
f.write(pretty_email)
f.close
I am not running into any errors, but I can't get it to write the data to the file. I know that the data is properly stored in the pretty_email variable because I can print it out in console.
Any thoughts?
MY UPDATED CODE THAT STILL DOESN'T WORK:
result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')
with open("da_email.txt", "w") as f:
f.write(pretty_email)
You need to invoke the close method to commit the changes to the file. Add ()
to the end:
f.close()
Or even better would be to use with
:
with open("da_email.txt", "w") as f:
f.write(pretty_email)
which automatically closes the file for you