Mark_1
Mark_1

Reputation: 643

Convert addresses from name <[email protected]> to phpmailer format

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 <[email protected]>, another display name <[email protected]>

Whereas PHPmailer takes each address in turn and passes the address and the display name as separate parameters eg:

$mail->addAddress('[email protected]','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

Upvotes: 4

Views: 1307

Answers (3)

Synchro
Synchro

Reputation: 37770

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 <[email protected]>, Jill User <[email protected]>';
foreach ($mail->parseAddresses($a) as $address) {
    $mail->addAddress($address['address'], $address['name']);
}

Upvotes: 7

Mark_1
Mark_1

Reputation: 643

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

Upvotes: 0

A. Blub
A. Blub

Reputation: 792

Here an example

$str = 'display name <[email protected]>, another display name <[email protected]>';
$targets = explode( ',', $str );

foreach( $targets as $target ) {
    list( $name, $email ) = explode( '<', $targert );
    $name = trim( $name );
    $email = str_replace( '>', '', $email );
    $mail->addAddress( $email, $name );
}

Upvotes: 1

Related Questions