Search code examples
phpemailgmailgmail-api

Get "From" and "To" addresses with Gmail API


I use Gmail API for retrieving messages from Gmail account and storing them in my DB. I want to store To/From email addresses for each message.

Each message contains headers array and within this array there are two fields like "From" and "To". However they also contain contact name, not a pure email address.

So right now I parse them like this:

if ($header->name === 'From') {
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $header->value, $matches);
    $from = $matches[0][0];
}

But is this the only way to get to/from adresses? Only by manually parsing headers?


Solution

  • Yes. The User.messages only includes from/to in standard RFC 2822 headers.

    You should avoid using regex to parse email addresses though. They are complex and can contain almost any character. See this regex for an example of what a compliant version would look like.