You are here

function phpmailer_smtp_parse_address in PHPMailer SMTP 2.x

Same name and namespace in other branches
  1. 8 phpmailer_smtp.module \phpmailer_smtp_parse_address()

Extract address and optional display name of an e-mail address.

Parameters

string $string: A string containing one or more valid e-mail address(es) separated with commas.

Return value

array An array containing all found e-mail addresses split into mail and name.

See also

http://tools.ietf.org/html/rfc5322#section-3.4

2 calls to phpmailer_smtp_parse_address()
PhpMailerSmtp::mail in src/Plugin/Mail/PhpMailerSmtp.php
Sends an e-mail message composed by drupal_mail().
PhpMailerSmtpUnitTest::testAddressParser in tests/src/Unit/PhpMailerSmtpUnitTest.php
Tests e-mail address extraction using phpmailer_smtp_parse_address().

File

./phpmailer_smtp.module, line 49
Uses the PHPMailer library to send emails via SMTP.

Code

function phpmailer_smtp_parse_address($string) {
  $parsed = [];

  // The display name may contain commas (3.4). Extract all quoted strings
  // (3.2.4) to a stack and replace them with a placeholder to prevent
  // splitting at wrong places.
  $string = preg_replace_callback('(".*?(?<!\\\\)")', '_phpmailer_smtp_stack', $string);

  // Build a regex that matches a name-addr (3.4).
  // @see valid_email_address()
  $user = '[a-zA-Z0-9_\\-\\.\\+\\^!#\\$%&*+\\/\\=\\?\\`\\|\\{\\}~\']+';
  $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.?)+';
  $ipv4 = '[0-9]{1,3}(?:\\.[0-9]{1,3}){3}';
  $ipv6 = '[0-9a-fA-F]{1,4}(?:\\:[0-9a-fA-F]{1,4}){7}';
  $address = "{$user}@(?:{$domain}|(?:\\[(?:{$ipv4}|{$ipv6})\\]))";
  $adr_rx = "/^(?P<name>.*)\\s<(?P<address>{$address})>\$/";

  // Split string into multiple parts and process each.
  foreach (explode(',', $string) as $email) {

    // Re-inject stripped placeholders.
    $email = preg_replace_callback('(\\x01)', '_phpmailer_smtp_stack', trim($email));

    // Check if it's a name-addr or a plain address (3.4).
    if (preg_match($adr_rx, $email, $matches)) {

      // PHPMailer expects an unencoded display name.
      $parsed[] = [
        'mail' => $matches['address'],
        'name' => Unicode::mimeHeaderDecode(stripslashes($matches['name'])),
      ];
    }
    else {
      $parsed[] = [
        'mail' => trim($email, '<>'),
        'name' => '',
      ];
    }
  }
  return $parsed;
}