Gmail API - ListUsersLabels - 没有邮件总数

Gmail API - ListUsersLabels - No messagesTotal

我正在使用 GMail API 检索我的标签: https://developers.google.com/gmail/api/v1/reference/users/labels/list

我的代码如下:

$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();
}

这一切通常似乎都有效,但它永远不会 returns 标签内的消息总数:

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
        (
        )

)

有人知道为什么会这样吗?

您需要标签 ID 来获取附加到它的邮件数量。首先执行List function to get all the labels, then take the Id of the label you need and use it in the Get函数。

以我为例 returns:

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

另一种方法是进行搜索查询,将消息 ID 存储在一个数组中,并获取长度:

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))