使用Gmail API获取“发件人”和“收件人”地址

时间:2021-09-14 15:25:10

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.

我使用Gmail API从Gmail帐户检索邮件并将其存储在我的数据库中。我想存储每封邮件的收件人/电子邮件地址。

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.

每条消息都包含头数组,在此数组中有两个字段,如“From”和“To”。但是,它们也包含联系人姓名,而不是纯电子邮件地址。

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?

但这是进出地址的唯一途径吗?只能通过手动解析标头?

2 个解决方案

#1


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

是。 User.messages仅包含标准RFC 2822标头中的from / to。

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.

您应该避免使用正则表达式来解析电子邮件地址。它们很复杂,几乎可以包含任何字符。请参阅此正则表达式,了解兼容版本的外观示例。

#2


I use imap_rfc822_parse_adrlist()

我用imap_rfc822_parse_adrlist()

It works like this:

它的工作原理如下:

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

I created small function which 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;
        }

#1


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

是。 User.messages仅包含标准RFC 2822标头中的from / to。

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.

您应该避免使用正则表达式来解析电子邮件地址。它们很复杂,几乎可以包含任何字符。请参阅此正则表达式,了解兼容版本的外观示例。

#2


I use imap_rfc822_parse_adrlist()

我用imap_rfc822_parse_adrlist()

It works like this:

它的工作原理如下:

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

I created small function which 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;
        }