Get From and To addresses using the Gmail API

I am using the Gmail API to fetch messages from a Gmail account and store them in my DB. I want to store the To / From email addresses for each message.

Each message contains an array of headers, and within that array there are two fields: "From" and "To". However, they also contain the contact's name rather than a blank email address.

So 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 addresses? Only by manually parsing the headers?

+3


source to share


2 answers


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



However, you shouldn't use a regular expression to parse email addresses. They are complex and can contain almost any character. See this regex for an example of what the corresponding version looks like.

+2


source


I am using imap_rfc822_parse_adrlist ()

It works like this:

$arrayOfAddressesFoundInString = imap_rfc822_parse_adrlist('Some Name <someemail@test.com>', 'localhost');

      



I created a small function that does the job for me:

function getAddressFromString($address_string) {
            $address_array  = imap_rfc822_parse_adrlist($address_string, "localhost");
            if (!is_array($address_array) || count($address_array) < 1) 
                return FALSE;
            return $address_array[0]->mailbox . '@' . $address_array[0]->host;
        }

      

0


source







All Articles