Draven
Draven

Reputation: 1467

PHP: Email Parsing - Multiple Recipients

I am piping email that get's sent to my server to a PHP script. The script parses the email so I can assign variables.

My problem is once in awhile somebody will include my email address to an email that's getting sent to multiple recipients and my script will only get the first one. I need it to find my email address then assign it to a variable.

Here is what the email array looks like: http://pastebin.com/0gdQsBYd

Using the example above I would need to get the 4th recipient: [email protected]

Here is the code I am using to get the "To -> name" and "To -> address"

# Get the name and email of the recipient
$toName = $results['To'][0]['name'];
$toEmail = $results['To'][0]['address'];

I assume I need to do a foreach($results['To'] as $to) then a preg_match but I am not good with regular expressions to find the email I want.

Some help is appreciated. Thank you.

Upvotes: 0

Views: 418

Answers (2)

Mic1780
Mic1780

Reputation: 1794

Actually, you do not need to use a regexp at all. Instead you can use a PHP for statement that loops through your array of To addresses.

$count = count($root['To']);
for ($i=0; $i < $count; $i++) {

    //Do something with your To array here using $root['To'][$i]['address']

}

Upvotes: 0

Ujwal Abhishek
Ujwal Abhishek

Reputation: 338

Instead of usin preg_match inside foreach loop you can use strstr like below

Supposing you are looking for [email protected] use following code

foreach($results['To'] as $to)
{

// gets value occuring before the @, if you change the 3 rd parameter to false returns domain name

$user = strstr($to, '@', true) ;
if($user == 'my_user_email')
{
//your action code goes here
}

} 

example:

<?php
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

Upvotes: 1

Related Questions