Search code examples
gmail-apiinboxprincipal

How to filter the Google Api inbox to read only the main messages?


I made a script to check if there are new emails in my inbox, but it returns the emails (Gmail) from the Main, Social and Promotions box, but I just want to read the one from the Main box.

Its an script for my IA

        # Call the Gmail API to fetch INBOX

        results = service.users().messages().list(userId='me',labelIds = ['INBOX', 'UNREAD']).execute()
        messages = results.get('messages', [])


        if not messages:
            frase = 'Sem novas mensagens na caixa de email'
            a = Pesquise(frase)
            a.fala(frase)
        else:
            for message in messages:
                msg = service.users().messages().get(userId='me', id=message['id']).execute()
                payld = msg['payload'] # get payload of the message 
                headr = payld['headers'] # get header of the payload
                for one in headr: # getting the Subject
                    if one['name'] == 'Subject':
                        msg_subject = remover_acentos(one['value'])
                    else:
                        pass
                frase = 'Hugo, novo email na caixa de entrada, ' + msg_subject
                a = Pesquise(frase)
                a.fala(frase)
        sleep(600)
except Exception as err:
    print err

I just want the script to read the Main box, not the Main, Social, and Promotions.


Solution

  • Based from SGC's answer, you can add the following q parameter on your Users.messages: list :

    in:inbox is:unread -category:(promotions OR social)
    

    The result will be something like:

    {
     "messages": [
      {
       "id": "169f891015afd26b",
       "threadId": "169f891015afd26b"
      },
      {
       "id": "169f67bfu70eed28",
       "threadId": "169f67bf5d0eed28"
      },
      {
       "id": "169f65c4bea507b9",
       "threadId": "169f27c4bea507b9"
      },
      {
       "id": "169ef58fd53f6c1d",
       "threadId": "169ef58fd53f6c1d"
      },
      {
       "id": "169eecy7846c17ca",
       "threadId": "169eecy7846c17ca"
      },
      {
       "id": "169ea5df63c40128",
       "threadId": "169ea5df63c40128"
      }
     ],
     "resultSizeEstimate": 6
    }
    

    You can try this here.