I have the following code:
import imaplib
import email
import codecs
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email@gmail.com', 'pass')
mail.list()
mail.select("inbox")
result, data = mail.uid('search', None, "ALL")
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = email_data[0][1]
email_message = email.message_from_string(raw_email)
save_string = str("/Users/Me/Desktop/Email/" + str(x) + ".txt")
myfile = open(save_string, 'a')
myfile.write(email_message)
myfile.close()
(I am trying to export all the email as a txt file.)
I get the error expected a character buffer object
.
Does anyone know why this would be?
Thanks
Edit: Error is in line myfile.write(email_message)
email.message_from_string(raw_email)
is not returning a string, but a Message
object instead. You cannot write Message
objects directly to a file without serializing them in some way.
您所要做的就是将email_message
转换为字符串。
myfile.write(str(email_message))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.