Skip to content

Instantly share code, notes, and snippets.

@leMaur
Last active February 13, 2025 10:13
Show Gist options
  • Save leMaur/c9ab1dc135a6fac9a8ef60fc7a92ab4a to your computer and use it in GitHub Desktop.
Save leMaur/c9ab1dc135a6fac9a8ef60fc7a92ab4a to your computer and use it in GitHub Desktop.
Convert UTF8 Email Address
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);
}
}
<?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]');
});
@leMaur
Copy link
Author

leMaur commented Feb 13, 2025

Platform
Laravel

How to use
Copy/paste this snippet inside helpers.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment