PYTHON: How to import undelivered gmail emails with Diagnostic-Code and Final-Recipient

70 Views Asked by At

I'm newbie to gmail api calls.

My goal is when an email failed to deliver to the target recipient, I'm trying to import Diagnostic-Code: and Final-Recipient: details.Below is the ultimate file what i'm trying to achieve. https://docs.google.com/spreadsheets/d/1ZxwyhgMxxnJBDo723bkOpy8mEELc7ascyBMF6-47oeQ/edit#gid=361779282

I have tried with several approaches, below is the sample code where i'm currently at, but this still doesn't return actual details that i was looking for such as actual Diagnostic-Code: and Final-Recipient detail.

def testme():       
    
    for i,msg in enumerate(dfmsgid['msg_id'].head(1)):
        z1=service.users().messages().get(userId="me",id=msg,format="raw").execute()
        message_with_bytes=base64.urlsafe_b64decode(z1['raw'].encode('ASCII'))            
        email_object=email.message_from_bytes(message_with_bytes)
        body=''
        if email_object.is_multipart():
            
            for part in email_object.walk():
                body=str(part.get_payload(decode=True))
                print("\n")
                print("printing multipart body")
                print(body)
        else:
            body=email_object.get_payload()
        
        print(body)
0

There are 0 best solutions below