Last active
February 13, 2025 10:13
-
-
Save leMaur/c9ab1dc135a6fac9a8ef60fc7a92ab4a to your computer and use it in GitHub Desktop.
Convert UTF8 Email Address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!function_exists('convert_utf8_email_address')) { | |
/** | |
* To maintain compatibility with older systems, Amazon SES honors the 7-bit ASCII limitation | |
* of SMTP as defined in RFC 2821. If you want to send content that contains non-ASCII | |
* characters, you must encode those characters into a format that uses | |
* 7-bit ASCII characters. | |
* | |
* @see https://docs.aws.amazon.com/ses/latest/dg/send-email-raw.html#send-email-mime-encoding-addresses | |
*/ | |
function convert_utf8_email_address(string $emailAddress): string { | |
if (\Illuminate\Support\Facades\Validator::make(['email' => $emailAddress], ['email' => 'email'])->fails()) { | |
return $emailAddress; | |
} | |
[$from, $domain] = explode('@', $emailAddress, limit: 2); | |
/** | |
* We need to convert the local part of the email address | |
* using MIME encoded-word syntax. | |
*/ | |
$from = mb_encode_mimeheader($from, mb_detect_encoding($from)); | |
/** | |
* We need to convert the domain part of the email address | |
* using Punycode (RFC 3492). | |
*/ | |
$domain = idn_to_ascii($domain, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); | |
return sprintf('%s@%s', $from, $domain); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
test('it_converts_utf8_email_address', function () { | |
expect(convert_utf8_email_address('thomâs.müller@groß.de'))->toBe('[email protected]'); | |
expect(convert_utf8_email_address('thomas.muller@groß.de'))->toBe('[email protected]'); | |
expect(convert_utf8_email_address('thomâs.mü[email protected]'))->toBe('[email protected]'); | |
}); | |
test('it_doesnt_convert_ascii_email_address', function () { | |
expect(convert_utf8_email_address('[email protected]'))->toBe('[email protected]'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Platform
Laravel
How to use
Copy/paste this snippet inside
helpers.php