IdnAddressEncoder.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Encoder;
  11. use Symfony\Component\Mime\Exception\AddressEncoderException;
  12. /**
  13. * An IDN email address encoder.
  14. *
  15. * Encodes the domain part of an address using IDN. This is compatible will all
  16. * SMTP servers.
  17. *
  18. * This encoder does not support email addresses with non-ASCII characters in
  19. * local-part (the substring before @). To send to such addresses, use
  20. * Utf8AddressEncoder together with SmtpUtf8Handler. Your outbound SMTP server must support
  21. * the SMTPUTF8 extension.
  22. *
  23. * @author Christian Schmidt
  24. */
  25. final class IdnAddressEncoder implements AddressEncoderInterface
  26. {
  27. /**
  28. * Encodes the domain part of an address using IDN.
  29. *
  30. * @throws AddressEncoderException If local-part contains non-ASCII characters
  31. */
  32. public function encodeString(string $address): string
  33. {
  34. $i = strrpos($address, '@');
  35. if (false !== $i) {
  36. $local = substr($address, 0, $i);
  37. $domain = substr($address, $i + 1);
  38. if (preg_match('/[^\x00-\x7F]/', $local)) {
  39. throw new AddressEncoderException(sprintf('Non-ASCII characters not supported in local-part os "%s".', $address));
  40. }
  41. if (preg_match('/[^\x00-\x7F]/', $domain)) {
  42. $address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46));
  43. }
  44. }
  45. return $address;
  46. }
  47. }