Convert addresses from name <address@domain.tld> to phpmailer format

懵懂的女人 提交于 2020-01-04 05:59:25

问题


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


回答1:


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']);
}



回答2:


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 );
}



回答3:


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



来源:https://stackoverflow.com/questions/30371748/convert-addresses-from-name-addressdomain-tld-to-phpmailer-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!