我正在尝试将打印精美的电子邮件写入 .txt 文件,以便更好地查看要从中解析的内容。
这是我的代码的这一部分:
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
我没有遇到任何错误,但我无法将数据写入文件。我知道数据已正确存储在 pretty_email 变量中,因为我可以在控制台中将其打印出来。
有什么想法吗?
我的更新代码仍然不起作用:
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)