I'm getting notifications using Pub/Sub, but the messageId I get is not the messageId to see the email content, how can I get this messageId?
I get this data on my endpoint
{
  message:
  {
    data:"eyJlbWFpbEFkZHJlc3MiOiAidXNlckBleGFtcGxlLmNXXXXXX,
    "messageId": "2070443601311540",
    "publishTime": "2021-02-26T19:13:55.749Z",
  }
  subscription: "projects/myproject/subscriptions/mysubscription"
}
The pub/sub messageId has nothing to do with the gmail messageId.
I need to get the messageId from gmail whenever a new email is received in my inbox.
You can get the historyId from the data part after base64 decoding it. By history id you can get all the messages that are being affected in that history record.
Save this historyId in your local DB or Json file.
next time whenever you receive a new notification from gmail pub/sub you have to call user_history->list by providing the previous history_id that you saved in DB. And save that latest historyId in your DB for future.
call users_history->listUsersHistory(), to get the history object.
The history object also have messagesAdded, messagesDeleted, labelsAdded, labeslRemoved Collection. In general messages collection you may get duplicate messages try being specific.
call usersMessages->get(), to get the specific message.
$service = new Google_Service_Gmail($client);
$response = $service->users_history->listUsersHistory('me', ['startHistoryId' => $historyId]);
$historyList = $response->getHistory();
foreach ($historyList as $history) {
    foreach ($history->messages as $message) {
        $message = $service->users_messages->get('me', $message->id);
    }
}
Note: if you try to get history record from the latest history Id (received in response) you will get nothing because that is the new history Id which contains nothing now. you have to get the history list starting from the previous history Id
for more details, read these https://developers.google.com/gmail/api/reference/rest/v1/users.history/list
https://medium.com/@eagnir/understanding-gmails-push-notifications-via-google-cloud-pub-sub-3a002f9350ef
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With