John
John

Reputation: 13

How to extract emails from full headers

I have some emails that I have opened with PHP and now need to get the sender's email addresses. Can someone tell me what function I need to use for this? I already have the emails opening with PHP.

EDIT: Is this a tough question or am I just not explaining it well enough?

Do I use preg_match to get the email addresses from the opened contents?

Upvotes: 1

Views: 2504

Answers (2)

Tim Lytle
Tim Lytle

Reputation: 17624

Some mail sending libraries can parse raw email, while not that well documented Zend_Mail should be able to do that by passing your raw email to a Zend_Mail_Message object. (Note: Reading mailboxes is well documented, from what I've seen, reading a raw message isn't.)

$message = new Zend_Mail_Message(array(), $filename);
$sender = $message->getHeader('From');

If all you need is the sender, then a good RegEx would be better to use, however, if you will be testing other headers/manipulating the body/mime parts, then using a library will be worth it.

Upvotes: 3

Atli
Atli

Reputation: 7930

Hey. You could use a regular expression for this.

$regexp = '/From:\s*(([^\<]*?) <)?<?(.+?)>?\s*\n/i';
if(preg_match($regexp, $email, $matches)) {
    echo "Name: " . $matches[2] . "\r\n";
    echo "Email: " . $matches[3] . "\r\n";
}
else {
    echo "No match";
}

The "Name" part would just be empty if no name was included.

That should work for the standard From header. This is assuming you are using the raw email, headers and all included.

Upvotes: 3

Related Questions