We have been using PEAR Mail but as this hasn't been maintained for a while I am wanting to convert to PHPmailer instead. We have an existing email class which wraps the actual mailer so conversion isn't looking too difficult so far.
The problem I have run into is that our existing sendEmail method expects email addresses as a string like
display name <address@domain.tld>, another display name <address2@domain.tld>
Whereas PHPmailer takes each address in turn and passes the address and the display name as separate parameters eg:
$mail->addAddress('address@domain.tld','display name');
I need a routine to parse the old style addresses and separate out the addresses from the display names; I can write this but I don't want to re-invent the wheel and I don't think I can be the first person who has come across this issue (though my searching has failed to find an existing solution).
Can anyone point me at an existing solution to this?
Edited because I had reversed the display name details
I've been meaning to get around to this for a while, as it's been sitting in the PHPMailer issues queue for a couple of years, so I finally did something about it.
In HEAD on GitHub, or PHPMailer 5.2.11 when it's released, you can do this:
$a = 'Joe User <joe@example.com>, Jill User <jill@example.net>';
foreach ($mail->parseAddresses($a) as $address) {
$mail->addAddress($address['address'], $address['name']);
}
Here an example
$str = 'display name <address@domain.tld>, another display name <address2@domain.tld>';
$targets = explode( ',', $str );
foreach( $targets as $target ) {
list( $name, $email ) = explode( '<', $targert );
$name = trim( $name );
$email = str_replace( '>', '', $email );
$mail->addAddress( $email, $name );
}
Thanks @A.Blub but I think the following is a slightly tidier solution. it uses a built in PHP function that I didn't know about before;
if (!empty($to)) {
$address_array = imap_rfc822_parse_adrlist($to, 'example.com');
foreach ($address_array as $id => $address)
$mail->addAddress($address->mailbox . '@' . $address->host, $address->personal);
}
I found this in the reply by @Gumbo to Get email address from mailbox string