1

What is the correct way to decode an html email body when working with Gmail api.

// Expected: "<p><strong>Test test</strong></p>"
$message = $gmail->users_messages->get('me', $messageId);
$payload = $message->getPayload();
$body = $payload->getBody()->data;
Log::info('Raw body:', [$body]); // "PHA-PHN0cm9uZz5UZXN0IHRlc3Q8L3N0cm9uZz48L3A-"
Log::info('Base64 decoded body:', [base64_decode($body)]); // NO OUTPUT
Log::info('UTF8 encoded body:', [utf8_encode($body)]); // "PHA-PHN0cm9uZz5UZXN0IHRlc3Q8L3N0cm9uZz48L3A-"
Log::info('Quote print decoded:', [quoted_printable_decode($body)]); // "PHA-PHN0cm9uZz5UZXN0IHRlc3Q8L3N0cm9uZz48L3A-"
Log::info('Quote print decoded:', [quoted_printable_decode(base64_decode($body)))]); // NO OUTPUT
Angad Dubey
  • 5,067
  • 7
  • 30
  • 51

1 Answers1

4

Figured it out. It needs some additional hackery, specifically a base64url_decode function found here

protected function base64url_decode($data) { 
        return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 

}

public function getMessage($messageId) {
    // ...
    $message = $gmail->users_messages->get('me', $messageId);
    $payload = $message->getPayload();
    $body = $payload->getBody()->data;
    // decoded body
    return $decodedBody= quoted_printable_decode($this->base64url_decode($rawBody));
}
Angad Dubey
  • 5,067
  • 7
  • 30
  • 51
  • Are you aware of any scripts that can actually filter the contents of the email body .e..g a receipt received in the email. The script should be able to filter out the item name, price , purchase date, tax etc. – user9465677 Jun 07 '18 at 05:35
  • @user9465677 sounds like you need something specific to your use case. – Angad Dubey Jun 17 '18 at 14:56