简体   繁体   中英

PHP Gmail Api - Delete Mail

How can I delete gmail mail after reading it? Tried looking everywhere but couldn't find the right solution for me. Currently the code below read subject and body, I want to delete that specific mail right after reading it

$service = new Google_Service_Gmail($client);
foreach ($messages as $message){
        $msg = $service->users_messages->get($userId, $message->getId());

        $headers = $msg->getPayload()->getHeaders();
        $subject = array_values(array_filter($headers, function($k){
            return $k['name'] == 'Subject';
        }));
        
        $subject = $subject[0]->getValue();
        $body = base64_decode(var_export($msg->payload->body->data, true)));
}

I believe your goal and situation as follows.

  • You want to delete the message using googleapis for php.
  • You have already been able to get and put values for Gmail API.

In this case, it uses the method of "users.messages.delete" in Gmail API.

Sample script:

When your script is modified, it becomes as follows.

$service = new Google_Service_Gmail($client);
foreach ($messages as $message){
    $msg = $service->users_messages->get($userId, $message->getId());

    $headers = $msg->getPayload()->getHeaders();
    $subject = array_values(array_filter($headers, function($k){
        return $k['name'] == 'Subject';
    }));
    
    $subject = $subject[0]->getValue();
    $body = base64_decode(var_export($msg->payload->body->data, true)));

    $service->users_messages->delete($userId, $message->getId());  // Added
}
  • the method of "users.messages.delete" returns no values. Please be careful this.

Note:

  • In this case, it supposes that $service can be used for deleting the message. If an error related to the scopes occurs, please add the scope of https://mail.google.com/ and test it again. But when the scope is changed, please the file including the access token and refresh token and authorize again. By this, the new scopes are reflected to the access token and refresh token. Please be careful this.

    • For example, if in your current script, the scope is used like $client->setScopes(Google_Service_Gmail::GMAIL_READONLY); , please modify it to $client->setScopes("https://mail.google.com/"); . And authorize it again.
  • IMPORTANT

    • In this modified script, the message is completely deleted. So I would like to recommend to test it using a sample message. Please be careful this.

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM