John Magnolia
John Magnolia

Reputation: 16793

Get from email address with email parser

I am using this absolute amazing piece of code: https://github.com/plancake/official-library-php-email-parser/blob/master/PlancakeEmailParser.php

But the one thing it is missing is the ability to get the From email address.

I have simple added:

public function getFromEmail()
{
    if (!isset($this->rawFields['from']))
    {
        return false;
    }

    return $this->rawFields['from'];
}

But how would I get only the email address part at the moment it returns: John Smith<[email protected]>?

Also I would need this to work if the From address was only [email protected]?

Thanks to the answers this was the finished code:

public function getFromEmail()
{
    $email = trim($this->rawFields['from']);

    if(substr($email, -1) == '>'){
        $fromarr = explode("<",$email);
        $mailarr1 = explode(">",$fromarr[1]);
        $email = $mailarr1[0];
    }

    return $email;
}

Upvotes: 0

Views: 253

Answers (2)

AStupidNoob
AStupidNoob

Reputation: 2050

This is a very simple regular expression:

$output = array();
preg_match("/.*<(.*?)>.*?/", $this->rawFields['from'], $output);
$email_address = $output[1];

Care though: If someone's name contains < or > it might cause a security vulnerability. The lazy operator (*.?) is used to ensure the last set of < > is used.

HTH

PS: Use http://gskinner.com/RegExr/ to test Regular Expressions!

Upvotes: 2

Suyash
Suyash

Reputation: 625

$mailid='John Smith<[email protected]>';
$mailarr=explode("<",$mailid);
$mailarr1=explode(">",$mailarr[1]);
$just_emailid=$mailarr1[0];

Upvotes: 0

Related Questions