Search code examples
pythongmail-apitostring

Convert message object to string (Gmail api and python)


I am trying to save only a specific part of an email using python. I have the variables service, userId and msg_id but I don't know how to convert the variable plainText to a string in order to take the part that I want in the get_info function

def get_message(service, user_id, msg_id):
    try:
        #get the message in raw format
        message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
        
        #encode the message in ASCII format
        msg_str = base64.urlsafe_b64decode(message['raw'].encode("ASCII")).decode("ASCII")
        #put it in an email object
        mime_msg = email.message_from_string(msg_str)
        #get the plain and html text from the payload
        plainText, htmlText = mime_msg.get_payload()
            
        print(get_info(plainText, "start", "finish"))
    except Exception as error:
        print('An error occurred in the get_message function: %s' % error)

def get_info(plainText, start, end):    
    
    usefullText = plainText.split(start)[2]
    usefullText = usefullText.split(end)[0]
    return usefullText
    

after running the code I have the following error message:

An error occurred in the get_message function: 'Message' object has no attribute 'split'


Solution

  • Answer:

    The method get_payload() doesn't exist for the email.message class. You need to use as_string() instead.

    Code Fix:

    The code inside your try block needs to be updated, from:

    #get the plain and html text from the payload
    plainText, htmlText = mime_msg.get_payload()
    

    to:

    #get the plain and html text from the payload
    plainText, htmlText = mime_msg.as_string() 
    

    References: