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.
In this case, it uses the method of "users.messages.delete" in Gmail API.
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
}
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.
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
, please modify it to $client->setScopes("https://mail.google.com/");
. And authorize it again.IMPORTANT
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.