Format a pair of (name, address) or an email address string.
(addr, encoding)
| 105 | |
| 106 | # RemovedInDjango70Warning. |
| 107 | def sanitize_address(addr, encoding): |
| 108 | """ |
| 109 | Format a pair of (name, address) or an email address string. |
| 110 | """ |
| 111 | warnings.warn( |
| 112 | "The internal API sanitize_address() is deprecated." |
| 113 | " Python's modern email API (with email.message.EmailMessage or" |
| 114 | " email.policy.default) will handle most required validation and" |
| 115 | " encoding. Use Python's email.headerregistry.Address to construct" |
| 116 | " formatted addresses from component parts.", |
| 117 | RemovedInDjango70Warning, |
| 118 | ) |
| 119 | |
| 120 | address = None |
| 121 | if not isinstance(addr, tuple): |
| 122 | addr = force_str(addr) |
| 123 | try: |
| 124 | token, rest = parser.get_mailbox(addr) |
| 125 | except (HeaderParseError, ValueError, IndexError): |
| 126 | raise ValueError('Invalid address "%s"' % addr) |
| 127 | else: |
| 128 | if rest: |
| 129 | # The entire email address must be parsed. |
| 130 | raise ValueError( |
| 131 | 'Invalid address; only %s could be parsed from "%s"' % (token, addr) |
| 132 | ) |
| 133 | nm = token.display_name or "" |
| 134 | localpart = token.local_part |
| 135 | domain = token.domain or "" |
| 136 | else: |
| 137 | nm, address = addr |
| 138 | if "@" not in address: |
| 139 | raise ValueError(f'Invalid address "{address}"') |
| 140 | localpart, domain = address.rsplit("@", 1) |
| 141 | |
| 142 | address_parts = nm + localpart + domain |
| 143 | if "\n" in address_parts or "\r" in address_parts: |
| 144 | raise ValueError("Invalid address; address parts cannot contain newlines.") |
| 145 | |
| 146 | # Avoid UTF-8 encode, if it's possible. |
| 147 | try: |
| 148 | nm.encode("ascii") |
| 149 | nm = Header(nm).encode() |
| 150 | except UnicodeEncodeError: |
| 151 | nm = Header(nm, encoding).encode() |
| 152 | try: |
| 153 | localpart.encode("ascii") |
| 154 | except UnicodeEncodeError: |
| 155 | localpart = Header(localpart, encoding).encode() |
| 156 | domain = punycode(domain) |
| 157 | |
| 158 | parsed_address = Address(username=localpart, domain=domain) |
| 159 | return formataddr((nm, parsed_address.addr_spec)) |
| 160 | |
| 161 | |
| 162 | # RemovedInDjango70Warning. |