0
votes

I'm using the GMail API to retrieve my labels: https://developers.google.com/gmail/api/v1/reference/users/labels/list

My code is as follows:

$userId = 'me';

$labels = array();

try {
    $labelsResponse = $service->users_labels->listUsersLabels($userId);

    if ($labelsResponse->getLabels()) {
        $labels = array_merge($labels, $labelsResponse->getLabels());
    }

    foreach ($labels as $label) {
        echo "<pre>";
        print_r($label);
        echo "</pre>";
    }
} catch (Excetion $e) {
    print 'An error occurred: ' . $e->getMessage();
}

This all generally seems to work however it never returns the total number of messages within the label:

Google_Service_Gmail_Label Object
(
    [colorType:protected] => Google_Service_Gmail_LabelColor
    [colorDataType:protected] => 
    [id] => INBOX
    [labelListVisibility] => labelShow
    [messageListVisibility] => hide
    [messagesTotal] => 
    [messagesUnread] => 
    [name] => INBOX
    [threadsTotal] => 
    [threadsUnread] => 
    [type] => system
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
        )

    [processed:protected] => Array
        (
        )

)

Does anyone know why this would be?

1

1 Answers

0
votes

You need the Label Id to get the number of messages attached to it. First execute the List function to get all the labels, then take the Id of the label you need and use it in the Get function.

In my case this returns:

{
 "id": "Label_ID",
 "name": "labelName",
 "type": "user",
 "messagesTotal": 11,
 "messagesUnread": 0,
 "threadsTotal": 11,
 "threadsUnread": 0
}

Another way is doing a search query, store the message IDs in an array, and get the length:

def get_emails():
        user_id = 'me' #Your email
        mail_ids = []
        query = 'label:your_label' 
        response = mail_service.users().messages().list(userId=user_id, q=query).execute()
        items = response.get('messages', [])
        if not items:
                print('No mails found')
                sys.exit()
        else:
                for items in items:
                        mail_ids.append(items['id'])
        print(len(mail_ids))