PHP code example of mmucklo / email-parse

1. Go to this page and download the library: Download mmucklo/email-parse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mmucklo / email-parse example snippets


use Email\Parse;

// Array-based API (v2.x-compatible)
$result = Parse::getInstance()->parse("[email protected] [email protected]");

// Typed value objects (v3.1+, recommended for new code)
$address = Parse::getInstance()->parseSingle('[email protected]');
echo $address->localPart;           // "john"
echo $address->domain;              // "example.com"
if ($address->invalid) {
    echo $address->invalidReasonCode->value;
}

$result = Parse::getInstance()->parseMultiple('[email protected], [email protected]');
foreach ($result->emailAddresses as $addr) { /* ... */ }

// Streaming for large batches (v3.2+) — yields one address at a time.
foreach (Parse::getInstance()->parseStream($csvRows) as $addr) {
    if ($addr->invalid) continue;
    // ...
}

// Serialization (v3.3+)
$parsed = Parse::getInstance()->parseSingle('"J Doe" <[email protected]>');
(string) $parsed;        // "[email protected]" — Stringable returns simple_address
$parsed->canonical();    // 'J Doe <[email protected]>' — minimal RFC 5322 quoting
$parsed->toArray();      // legacy array shape, for mixed-API code
$parsed->toJson();       // JSON string

use Email\Parse;
use Email\ParseOptions;

// Example 1: Use comma and semicolon as separators (default behavior aa.com; [email protected], [email protected]");

// Example 2: Disable whitespace as separator (only comma and semicolon work)
$options = new ParseOptions([], [',', ';'], false);
$parser = new Parse(null, $options);
$result = $parser->parse("[email protected]; [email protected]"); // Works - uses semicolon
$result = $parser->parse("[email protected] [email protected]");  // Won't split - whitespace not a separator

// Example 3: Names with spaces always work regardless of whitespace separator setting
$options = new ParseOptions([], [',', ';'], false);
$parser = new Parse(null, $options);
$result = $parser->parse("John Doe <[email protected]>, Jane Smith <[email protected]>");
// Returns 2 valid emails with names preserved

use Email\Parse;
use Email\ParseOptions;

// RFC 5321 — Strict ASCII (SMTP Mailbox syntax)
$options = ParseOptions::rfc5321();
$parser = new Parse(null, $options);

// RFC 6531 — Strict Internationalized (full UTF-8 + NFC normalization)
$options = ParseOptions::rfc6531();
$parser = new Parse(null, $options);
$result = $parser->parseSingle('müller@münchen.de');  // Valid UTF-8 address

// RFC 5322 — Standard with obsolete syntax support (recommended)
$options = ParseOptions::rfc5322();
$parser = new Parse(null, $options);

// RFC 2822 — Maximum compatibility
$options = ParseOptions::rfc2822();
$parser = new Parse(null, $options);

// Legacy — v2.x default behavior
$options = new ParseOptions();
$parser = new Parse(null, $options);

// UTF-8 email address validation
$options = ParseOptions::rfc6531();
$parser = new Parse(null, $options);

$result = $parser->parseSingle('José.García@españa.es');
// Valid: UTF-8 characters allowed in rfc6531() preset

$result = $parser->parseSingle('[email protected]');
// Invalid: Leading dot not allowed (dot-atom restrictions still apply)

$options = ParseOptions::rfc6531()
    ->withRequireFqdn(false)          // Allow single-label domains
    ->withIncludeDomainAscii(false);  // Don't output punycode domain
$parser = new Parse(null, $options);

/**
 * @param array $bannedChars Array of characters to ban from email addresses (e.g., ['%', '!'])
 * @param array $separators Array of separator characters (default: [','])
 * @param bool $useWhitespaceAsSeparator Whether to treat whitespace/newlines as separators (default: true)
 * @param LengthLimits|null $lengthLimits Email length limits. Uses RFC defaults if not provided
 */
public function __construct(
    array $bannedChars = [],
    array $separators = [','],
    bool $useWhitespaceAsSeparator = true,
    ?LengthLimits $lengthLimits = null
)

use Email\Parse;
use Email\ParseOptions;
use Email\LengthLimits;

// Use default RFC-compliant limits (64, 254, 63)
$options = new ParseOptions([], [','], true, LengthLimits::createDefault());

// Use relaxed limits for legacy systems (128, 512, 128)
$options = new ParseOptions([], [','], true, LengthLimits::createRelaxed());

// Custom limits
$limits = new LengthLimits(
    100,  // maxLocalPartLength (before @)
    300,  // maxTotalLength (entire email)
    100   // maxDomainLabelLength (each domain label)
);
$options = new ParseOptions([], [','], true, $limits);
$parser = new Parse(null, $options);

$options = ParseOptions::rfc6531();
$parser = new Parse(null, $options);
$result = $parser->parseSingle('user@bücher.de');
// $result->domain      === 'bücher.de'
// $result->domainAscii === 'xn--bcher-kva.de'

use Email\Parse;

// Single comment
$result = Parse::getInstance()->parseSingle('[email protected] (home address)');
// $result->comments === ['home address']

// Multiple comments
$result = Parse::getInstance()->parseSingle('test(comment1)(comment2)@example.com');
// $result->comments === ['comment1', 'comment2']

// Nested comments
$result = Parse::getInstance()->parseSingle('[email protected] (comment with (nested) parens)');
// $result->comments === ['comment with (nested) parens']

// No comments
$result = Parse::getInstance()->parseSingle('[email protected]');
// $result->comments === []

// v2.x default (legacy behavior — still works in v3.0)
$parser = Parse::getInstance();

// v3.0 recommended default
$options = ParseOptions::rfc5322();
$parser = new Parse(null, $options);

// Use the rfc6531() preset for full internationalized email support
$options = ParseOptions::rfc6531();
$parser = new Parse(null, $options);
$result = $parser->parseSingle('müller@münchen.de');

/**
 * function parse($emails, $multiple = true, $encoding = 'UTF-8')
 * @param string $emails List of Email addresses separated by configured separators (comma, semicolon, whitespace by default)
 * @param bool $multiple (optional, default: true) Whether to parse for multiple email addresses or not
 * @param string $encoding (optional, default: 'UTF-8') The encoding if not 'UTF-8'
 * @return: see below: */

    if ($multiple):
         array('success' => boolean, // whether totally successful or not
               'reason' => string|null, // if unsuccessful, the reason why; null if successful
               'email_addresses' =>
                    array('address' => string, // the full address (not including comments)
                        'original_address' => string, // the full address including comments
                        'simple_address' => string, // simply local_part@domain_part (e.g. [email protected])
                         'name' => string, // the name on the email if given (e.g.: John Q. Public), including any quotes
                         'name_parsed' => string, // the name on the email if given (e.g.: John Q. Public), excluding any quotes
                        'local_part' => string, // the local part (before the '@' sign - e.g. johnpublic)
                        'local_part_parsed' => string, // the local part (before the '@' sign - e.g. johnpublic), excluding any quotes
                        'domain' => string, // the domain after the '@' if given (may be Unicode)
                        'domain_ascii' => string|null, // punycode ASCII domain (when ll if valid
            'comments' => array) // array of extracted comments (e.g. ['comment1', 'comment2'])
    endif;

 $email = '"J Doe" <[email protected]>';
 $result = Email\Parse::getInstance()->parse($email, false);

 $result == array(
     'address' => '"J Doe" <[email protected]>',
     'original_address' => '"J Doe" <[email protected]>',
     'simple_address' => '[email protected]',
     'name' => '"J Doe"',
     'name_parsed' => 'J Doe',
     'local_part' => 'johndoe',
     'local_part_parsed' => 'johndoe',
     'domain_part' => 'xyz.com',
     'domain' => 'xyz.com',
     'domain_ascii' => null,
     'ip' => '',
     'invalid' => false,
     'invalid_reason' => null,
     'comments' => []);

 $emails = 'testing@[8.8.8.8] [email protected], "test.2"@xyz.com (comment)';
 $result = Email\Parse::getInstance()->parse($emails);
 $result == array(
     'success' => true,
     'reason' => null,
     'email_addresses' => array(
         array(
             'address' => 'testing@[8.8.8.8]',
             'original_address' => 'testing@[8.8.8.8]',
             'simple_address' => 'testing@[8.8.8.8]',
             'name' => '',
             'name_parsed' => '',
             'local_part' => 'testing',
             'local_part_parsed' => 'testing',
             'domain_part' => '[8.8.8.8]',
             'domain' => '',
             'domain_ascii' => null,
             'ip' => '8.8.8.8',
             'invalid' => false,
             'invalid_reason' => null,
             'comments' => []),
         array(
             'address' => '[email protected]',
             'original_address' => '[email protected]',
             'simple_address' => '[email protected]',
             'name' => '',
             'name_parsed' => '',
             'local_part' => 'testing',
             'local_part_parsed' => 'testing',
             'domain_part' => 'xyz.com',
             'domain' => 'xyz.com',
             'domain_ascii' => null,
             'ip' => '',
             'invalid' => false,
             'invalid_reason' => null,
             'comments' => []),
         array(
             'address' => '"test.2"@xyz.com',
             'original_address' => '"test.2"@xyz.com (comment)',
             'simple_address' => '"test.2"@xyz.com',
             'name' => '',
             'name_parsed' => '',
             'local_part' => '"test.2"',
             'local_part_parsed' => 'test.2',
             'domain_part' => 'xyz.com',
             'domain' => 'xyz.com',
             'domain_ascii' => null,
             'ip' => '',
             'invalid' => false,
             'invalid_reason' => null,
             'comments' => ['comment'])
     )
 );