flo flo - 2 months ago 48
PHP Question

Create a filter using Gmail API

Google released recently a new version of its Gmail API which now makes possible to create filters.

However the documentation is quite limited and I'm facing issues to get it working. I'm using the latest version of their PHP client. Any help would be appreciated to construct the request body.

public $gmail;
public function createFilter($userId) {

try {

$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters();
// Here, we should create the request body...
// https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
// $filter->setCriteria() ??

$this->gmail->users_settings_filters->create($userId, $filter);


} catch (Exception $e) {
// Logging errors...
}

}


UPDATE (Working method)

public $gmail;
public function createFilter($userId) {

try {

$filter = new Google_Service_Gmail_Filter([
'criteria' => [
'from' => 'example@gmail.com'
],
'action' => [
'addLabelIds' => ['STARRED']
]
]);

$this->gmail->users_settings_filters->create($userId, $filter);


} catch (Exception $e) {
// Logging errors...
}

}

Answer

See https://github.com/google/google-api-php-client#making-requests for guidance on constructing request objects. You should be able to populate the filter properties using native PHP arrays or the autogenerated objects. Example:

$filter = new Google_Service_Gmail_Resource_UsersSettingsFilters([
    'criteria' => [
        'from' => 'somebody@example.com'
    ],
    'action' => [
        'addLabelIds' => ['STARRED']
    ]
]);
Comments