Python - Expected a character buffer object?

16,340

Solution 1

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.

Solution 2

All you have to do is to convert email_message to a string.

myfile.write(str(email_message))
Share:
16,340
samiles
Author by

samiles

Updated on June 05, 2022

Comments

  • samiles
    samiles almost 2 years

    I have the following code:

    import imaplib
    import email
    import codecs
    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login('[email protected]', '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)