IdnAddressEncoder.php 1.5 KB

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