2
votes

I am using the gmail api and when I try to get the "From" field from a specific message, I get the name portion but not the address. Here is the query that works in the oauth2 playground:

GET https://www.googleapis.com/gmail/v1/users/me/messages/14jj4883c9e195a8?format=metadata&metadataHeaders=From&fields=payload%2CsizeEstimate

It outputs:

{
    "payload": {
        "mimeType": "multipart/mixed",
        "headers": [
            {
                "name": "From",
                "value": "First Last <[email protected]>"
            }
        ]
    },
    "sizeEstimate": 180758
}

Implementing the same query in php:

function getMessage($service, $userId, $messageId) {
  try {
    $optParamsGet = array();    
    $optParamsGet['format'] = 'metadata';
    $optParamsGet['metadataHeaders'] = 'From';
    $optParamsGet['fields'] = 'payload,sizeEstimate';

    $message = $service->users_messages->get($userId, $messageId, $optParamsGet);
    print 'Message with ID: ' . $message->getId() . ' retrieved.<br>';
    return $message;
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
}

$message2 = getMessage($service,$userId,$message_id);

            if ($message2->getPayload()) {
                $headers = $message2->getPayload()->getHeaders(); 
                foreach ($headers as $header) {
                    if ('From' == $header->name) {
                        $name_value = $header->value;
                        echo $name_value . "<br>";
                        array_push($sendernames,$name_value);
                        echo $header['value']. "<br>";
                        break;
                    }
                }
            } 
            var_dump($headers);

And now, doing a var_dump on the headers in the returned $message does not show the email address within the angle bracket. How do I get this?

2
If you're echo-ing the value directly to an HTML document, you're going to want to pipe it through htmlspecialchars(), eg echo htmlspecialchars($name_value) - Phil

2 Answers

0
votes

The value should definitely be there in the from header. I agree with phil, I think it's likely your "<" and ">" are getting hidden/removed since you're printing to html output source. :)

0
votes

I had the same problem, I just used regex to get the email from the "First Last <[email protected]>" as far as I saw there was nowhere in the headers that had just the email address