1from .exceptions import EmailSyntaxError
2from .types import ValidatedEmail
3from .rfc_constants import EMAIL_MAX_LENGTH, LOCAL_PART_MAX_LENGTH, DOMAIN_MAX_LENGTH, \
4 DOT_ATOM_TEXT, DOT_ATOM_TEXT_INTL, ATEXT_RE, ATEXT_INTL_DOT_RE, ATEXT_HOSTNAME_INTL, QTEXT_INTL, \
5 DNS_LABEL_LENGTH_LIMIT, DOT_ATOM_TEXT_HOSTNAME, DOMAIN_NAME_REGEX, DOMAIN_LITERAL_CHARS
6
7import re
8import unicodedata
9import idna # implements IDNA 2008; Python's codec is only IDNA 2003
10import ipaddress
11from typing import Optional, TypedDict
12
13
14def split_email(email: str) -> tuple[Optional[str], str, str, bool, str]:
15 # Return the display name, the original local part, the unescaped
16 # local part, and the domain part of the address. If no
17 # display name was present and angle brackets do not surround
18 # the address, display name will be None; otherwise, it will be
19 # set to the display name or the empty string if there were
20 # angle brackets but no display name.
21
22 # Typical email addresses have a single @-sign and no quote
23 # characters, but the awkward "quoted string" local part form
24 # (RFC 5321 4.1.2) allows @-signs and escaped quotes to appear
25 # in the local part if the local part is quoted.
26
27 # A `display name <addr>` format is also present in MIME messages
28 # (RFC 5322 3.4) and this format is also often recognized in
29 # mail UIs. It's not allowed in SMTP commands or in typical web
30 # login forms, but parsing it has been requested, so it's done
31 # here as a convenience. It's implemented in the spirit but not
32 # the letter of RFC 5322 3.4 because MIME messages allow newlines
33 # and comments as a part of the CFWS rule, but this is typically
34 # not allowed in mail UIs (although comment syntax was requested
35 # once too).
36 #
37 # Display names are either basic characters (the same basic characters
38 # permitted in email addresses, but periods are not allowed and spaces
39 # are allowed; see RFC 5322 Appendix A.1.2), or a quoted string with
40 # the same rules as a quoted local part. (Multiple quoted strings might
41 # be allowed? Unclear.) Optional space (RFC 5322 3.4 CFWS) and then the
42 # email address follows in angle brackets.
43 #
44 # An initial quote is ambiguous between starting a display name or
45 # a quoted local part --- fun.
46 #
47 # We assume the input string is already stripped of leading and
48 # trailing CFWS.
49
50 def split_string_at_unquoted_special(text: str, specials: tuple[str, ...]) -> tuple[str, str]:
51 # Split the string at the first character in specials (an @-sign
52 # or left angle bracket) that does not occur within quotes and
53 # is not followed by a Unicode combining character.
54 # If no special character is found, raise an error.
55 inside_quote = False
56 escaped = False
57 left_part = ""
58 for i, c in enumerate(text):
59 # < plus U+0338 (Combining Long Solidus Overlay) normalizes to
60 # ≮ U+226E (Not Less-Than), and it would be confusing to treat
61 # the < as the start of "<email>" syntax in that case. Likewise,
62 # if anything combines with an @ or ", we should probably not
63 # treat it as a special character.
64 #
65 # Only the characters right after c can combine with it, so
66 # look at a short window rather than normalizing the rest of
67 # the string at every position, which is quadratic in the
68 # length of the input. The window is c, the 30 combining
69 # characters in a row allowed by the Unicode Stream-Safe Text
70 # Format (UAX #15), and one more character.
71 if unicodedata.normalize("NFC", text[i:i + 32])[0] != c:
72 left_part += c
73
74 elif inside_quote:
75 left_part += c
76 if c == '\\' and not escaped:
77 escaped = True
78 elif c == '"' and not escaped:
79 # The only way to exit the quote is an unescaped quote.
80 inside_quote = False
81 escaped = False
82 else:
83 escaped = False
84 elif c == '"':
85 left_part += c
86 inside_quote = True
87 elif c in specials:
88 # When unquoted, stop before a special character.
89 break
90 else:
91 left_part += c
92
93 # No special symbol found. The special symbols always
94 # include an at-sign, so this always indicates a missing
95 # at-sign. The other symbol is optional.
96 if len(left_part) == len(text):
97 # The full-width at-sign might occur in CJK contexts.
98 # We can't accept it because we only accept addresess
99 # that are actually valid. But if this is common we
100 # may want to consider accepting and normalizing full-
101 # width characters for the other special symbols (and
102 # full-width dot is already accepted in internationalized
103 # domains) with a new option.
104 # See https://news.ycombinator.com/item?id=42235268.
105 if "@" in text:
106 raise EmailSyntaxError("The email address has the \"full-width\" at-sign (@) character instead of a regular at-sign.")
107
108 # Check another near-homoglyph for good measure because
109 # homoglyphs in place of required characters could be
110 # very confusing. We may want to consider checking for
111 # homoglyphs anywhere we look for a special symbol.
112 if "﹫" in text:
113 raise EmailSyntaxError('The email address has the "small commercial at" character instead of a regular at-sign.')
114
115 raise EmailSyntaxError("An email address must have an @-sign.")
116
117 # The right part is whatever is left.
118 right_part = text[len(left_part):]
119
120 return left_part, right_part
121
122 def unquote_quoted_string(text: str) -> tuple[str, bool]:
123 # Remove surrounding quotes and unescape escaped backslashes
124 # and quotes. Escapes are parsed liberally. I think only
125 # backslashes and quotes can be escaped but we'll allow anything
126 # to be.
127 quoted = False
128 escaped = False
129 value = ""
130 for i, c in enumerate(text):
131 if quoted:
132 if escaped:
133 value += c
134 escaped = False
135 elif c == '\\':
136 escaped = True
137 elif c == '"':
138 if i != len(text) - 1:
139 raise EmailSyntaxError("Extra character(s) found after close quote: "
140 + ", ".join(safe_character_display(c) for c in text[i + 1:]))
141 break
142 else:
143 value += c
144 elif i == 0 and c == '"':
145 quoted = True
146 else:
147 value += c
148
149 return value, quoted
150
151 # Split the string at the first unquoted @-sign or left angle bracket.
152 left_part, right_part = split_string_at_unquoted_special(email, ("@", "<"))
153
154 # If the right part starts with an angle bracket,
155 # then the left part is a display name and the rest
156 # of the right part up to the final right angle bracket
157 # is the email address, .
158 if right_part.startswith("<"):
159 # Remove space between the display name and angle bracket.
160 left_part = left_part.rstrip()
161
162 # Unquote and unescape the display name.
163 display_name, display_name_quoted = unquote_quoted_string(left_part)
164
165 # Check that only basic characters are present in a
166 # non-quoted display name.
167 if not display_name_quoted:
168 bad_chars = {
169 safe_character_display(c)
170 for c in display_name
171 if (not ATEXT_RE.match(c) and c != ' ') or c == '.'
172 }
173 if bad_chars:
174 raise EmailSyntaxError("The display name contains invalid characters when not quoted: " + ", ".join(sorted(bad_chars)) + ".")
175
176 # Check for other unsafe characters.
177 check_unsafe_chars(display_name, allow_space=True)
178
179 # Check that the right part ends with an angle bracket
180 # but allow spaces after it, I guess.
181 if ">" not in right_part:
182 raise EmailSyntaxError("An open angle bracket at the start of the email address has to be followed by a close angle bracket at the end.")
183 right_part = right_part.rstrip(" ")
184 if right_part[-1] != ">":
185 raise EmailSyntaxError("There can't be anything after the email address.")
186
187 # Remove the initial and trailing angle brackets.
188 addr_spec = right_part[1:-1]
189
190 # Split the email address at the first unquoted @-sign.
191 local_part, domain_part = split_string_at_unquoted_special(addr_spec, ("@",))
192
193 # Otherwise there is no display name. The left part is the local
194 # part and the right part is the domain.
195 else:
196 display_name = None
197 local_part, domain_part = left_part, right_part
198
199 if domain_part.startswith("@"):
200 domain_part = domain_part[1:]
201
202 # Unquote the local part if it is quoted.
203 local_part_unquoted, is_quoted_local_part = unquote_quoted_string(local_part)
204
205 return display_name, local_part, local_part_unquoted, is_quoted_local_part, domain_part
206
207
208def get_length_reason(addr: str, limit: int) -> str:
209 """Helper function to return an error message related to invalid length."""
210 diff = len(addr) - limit
211 suffix = "s" if diff > 1 else ""
212 return f"({diff} character{suffix} too many)"
213
214
215def safe_character_display(c: str) -> str:
216 # Return safely displayable characters in quotes.
217 if c == '\\':
218 return f"\"{c}\"" # can't use repr because it escapes it
219 if unicodedata.category(c)[0] in ("L", "N", "P", "S"):
220 return repr(c)
221
222 # Construct a hex string in case the unicode name doesn't exist.
223 if ord(c) < 0xFFFF:
224 h = f"U+{ord(c):04x}".upper()
225 else:
226 h = f"U+{ord(c):08x}".upper()
227
228 # Return the character name or, if it has no name, the hex string.
229 return unicodedata.name(c, h)
230
231
232class LocalPartValidationResult(TypedDict):
233 local_part: str
234 ascii_local_part: Optional[str]
235 smtputf8: bool
236
237
238def validate_email_local_part(local: str, allow_smtputf8: bool = True, allow_empty_local: bool = False,
239 quoted_local_part: bool = False, strict: bool = False) -> LocalPartValidationResult:
240 """Validates the syntax of the local part of an email address."""
241
242 if len(local) == 0:
243 if not allow_empty_local:
244 raise EmailSyntaxError("There must be something before the @-sign.")
245
246 # The caller allows an empty local part. Useful for validating certain
247 # Postfix aliases.
248 return {
249 "local_part": local,
250 "ascii_local_part": local,
251 "smtputf8": False,
252 }
253
254 # Check the length of the local part by counting characters.
255 # (RFC 5321 4.5.3.1.1)
256 # We're checking the number of characters here. If the local part
257 # is ASCII-only, then that's the same as bytes (octets). If it's
258 # internationalized, then the UTF-8 encoding may be longer, but
259 # that may not be relevant. We will check the total address length
260 # instead.
261 if strict and len(local) > LOCAL_PART_MAX_LENGTH:
262 reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH)
263 raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.")
264
265 # Check the local part against the non-internationalized regular expression.
266 # Most email addresses match this regex so it's probably fastest to check this first.
267 # (RFC 5322 3.2.3)
268 # All local parts matching the dot-atom rule are also valid as a quoted string
269 # so if it was originally quoted (quoted_local_part is True) and this regex matches,
270 # it's ok.
271 # (RFC 5321 4.1.2 / RFC 5322 3.2.4).
272 if DOT_ATOM_TEXT.match(local):
273 # It's valid. And since it's just the permitted ASCII characters,
274 # it's normalized and safe. If the local part was originally quoted,
275 # the quoting was unnecessary and it'll be returned as normalized to
276 # non-quoted form.
277
278 # Return the local part and flag that SMTPUTF8 is not needed.
279 return {
280 "local_part": local,
281 "ascii_local_part": local,
282 "smtputf8": False,
283 }
284
285 # The local part failed the basic dot-atom check. Try the extended character set
286 # for internationalized addresses. It's the same pattern but with additional
287 # characters permitted.
288 # RFC 6531 section 3.3.
289 valid: Optional[str] = None
290 requires_smtputf8 = False
291 if DOT_ATOM_TEXT_INTL.match(local):
292 # But international characters in the local part may not be permitted.
293 if not allow_smtputf8:
294 # Check for invalid characters against the non-internationalized
295 # permitted character set.
296 # (RFC 5322 3.2.3)
297 bad_chars = {
298 safe_character_display(c)
299 for c in local
300 if not ATEXT_RE.match(c)
301 }
302 if bad_chars:
303 raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
304
305 # Although the check above should always find something, fall back to this just in case.
306 raise EmailSyntaxError("Internationalized characters before the @-sign are not supported.")
307
308 # It's valid.
309 valid = "dot-atom"
310 requires_smtputf8 = True
311
312 # There are no dot-atom syntax restrictions on quoted local parts, so
313 # if it was originally quoted, it is probably valid. More characters
314 # are allowed, like @-signs, spaces, and quotes, and there are no
315 # restrictions on the placement of dots, as in dot-atom local parts.
316 elif quoted_local_part:
317 # Check for invalid characters in a quoted string local part.
318 # (RFC 5321 4.1.2. RFC 5322 lists additional permitted *obsolete*
319 # characters which are *not* allowed here. RFC 6531 section 3.3
320 # extends the range to UTF8 strings.)
321 bad_chars = {
322 safe_character_display(c)
323 for c in local
324 if not QTEXT_INTL.match(c)
325 }
326 if bad_chars:
327 raise EmailSyntaxError("The email address contains invalid characters in quotes before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
328
329 # See if any characters are outside of the ASCII range.
330 bad_chars = {
331 safe_character_display(c)
332 for c in local
333 if not (32 <= ord(c) <= 126)
334 }
335 if bad_chars:
336 requires_smtputf8 = True
337
338 # International characters in the local part may not be permitted.
339 if not allow_smtputf8:
340 raise EmailSyntaxError("Internationalized characters before the @-sign are not supported: " + ", ".join(sorted(bad_chars)) + ".")
341
342 # It's valid.
343 valid = "quoted"
344
345 # If the local part matches the internationalized dot-atom form or was quoted,
346 # perform additional checks for Unicode strings.
347 if valid:
348 # Check that the local part is a valid, safe, and sensible Unicode string.
349 # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
350 # by DOT_ATOM_TEXT_INTL and QTEXT_INTL. Other characters may be permitted by the
351 # email specs, but they may not be valid, safe, or sensible Unicode strings.
352 # See the function for rationale.
353 check_unsafe_chars(local, allow_space=(valid == "quoted"))
354
355 # Try encoding to UTF-8. Failure is possible with some characters like
356 # surrogate code points, but those are checked above. Still, we don't
357 # want to have an unhandled exception later.
358 try:
359 local.encode("utf8")
360 except ValueError as e:
361 raise EmailSyntaxError("The email address contains an invalid character.") from e
362
363 # If this address passes only by the quoted string form, re-quote it
364 # and backslash-escape quotes and backslashes (removing any unnecessary
365 # escapes). Per RFC 5321 4.1.2, "all quoted forms MUST be treated as equivalent,
366 # and the sending system SHOULD transmit the form that uses the minimum quoting possible."
367 if valid == "quoted":
368 local = '"' + re.sub(r'(["\\])', r'\\\1', local) + '"'
369
370 return {
371 "local_part": local,
372 "ascii_local_part": local if not requires_smtputf8 else None,
373 "smtputf8": requires_smtputf8,
374 }
375
376 # It's not a valid local part. Let's find out why.
377 # (Since quoted local parts are all valid or handled above, these checks
378 # don't apply in those cases.)
379
380 # Check for invalid characters.
381 # (RFC 5322 3.2.3, plus RFC 6531 3.3)
382 bad_chars = {
383 safe_character_display(c)
384 for c in local
385 if not ATEXT_INTL_DOT_RE.match(c)
386 }
387 if bad_chars:
388 raise EmailSyntaxError("The email address contains invalid characters before the @-sign: " + ", ".join(sorted(bad_chars)) + ".")
389
390 # Check for dot errors imposted by the dot-atom rule.
391 # (RFC 5322 3.2.3)
392 check_dot_atom(local, 'An email address cannot start with a {}.', 'An email address cannot have a {} immediately before the @-sign.', is_hostname=False)
393
394 # All of the reasons should already have been checked, but just in case
395 # we have a fallback message.
396 raise EmailSyntaxError("The email address contains invalid characters before the @-sign.")
397
398
399def check_unsafe_chars(s: str, allow_space: bool = False) -> None:
400 # Check for unsafe characters or characters that would make the string
401 # invalid or non-sensible Unicode.
402 bad_chars = set()
403 for i, c in enumerate(s):
404 category = unicodedata.category(c)
405 if category[0] in ("L", "N", "P", "S"):
406 # Letters, numbers, punctuation, and symbols are permitted.
407 pass
408 elif category[0] == "M":
409 # Combining character in first position would combine with something
410 # outside of the email address if concatenated, so they are not safe.
411 # We also check if this occurs after the @-sign, which would not be
412 # sensible because it would modify the @-sign.
413 if i == 0:
414 bad_chars.add(c)
415 elif category == "Zs":
416 # Spaces outside of the ASCII range are not specifically disallowed in
417 # internationalized addresses as far as I can tell, but they violate
418 # the spirit of the non-internationalized specification that email
419 # addresses do not contain ASCII spaces when not quoted. Excluding
420 # ASCII spaces when not quoted is handled directly by the atom regex.
421 #
422 # In quoted-string local parts, spaces are explicitly permitted, and
423 # the ASCII space has category Zs, so we must allow it here, and we'll
424 # allow all Unicode spaces to be consistent.
425 if not allow_space:
426 bad_chars.add(c)
427 elif category[0] == "Z":
428 # The two line and paragraph separator characters (in categories Zl and Zp)
429 # are not specifically disallowed in internationalized addresses
430 # as far as I can tell, but they violate the spirit of the non-internationalized
431 # specification that email addresses do not contain line breaks when not quoted.
432 bad_chars.add(c)
433 elif category[0] == "C":
434 # Control, format, surrogate, private use, and unassigned code points (C)
435 # are all unsafe in various ways. Control and format characters can affect
436 # text rendering if the email address is concatenated with other text.
437 # Bidirectional format characters are unsafe, even if used properly, because
438 # they cause an email address to render as a different email address.
439 # Private use characters do not make sense for publicly deliverable
440 # email addresses.
441 bad_chars.add(c)
442 else:
443 # All categories should be handled above, but in case there is something new
444 # to the Unicode specification in the future, reject all other categories.
445 bad_chars.add(c)
446 if bad_chars:
447 raise EmailSyntaxError("The email address contains unsafe characters: "
448 + ", ".join(safe_character_display(c) for c in sorted(bad_chars)) + ".")
449
450
451def check_dot_atom(label: str, start_descr: str, end_descr: str, is_hostname: bool) -> None:
452 # RFC 5322 3.2.3
453 if label.endswith("."):
454 raise EmailSyntaxError(end_descr.format("period"))
455 if label.startswith("."):
456 raise EmailSyntaxError(start_descr.format("period"))
457 if ".." in label:
458 raise EmailSyntaxError("An email address cannot have two periods in a row.")
459
460 if is_hostname:
461 # RFC 952
462 if label.endswith("-"):
463 raise EmailSyntaxError(end_descr.format("hyphen"))
464 if label.startswith("-"):
465 raise EmailSyntaxError(start_descr.format("hyphen"))
466 if ".-" in label or "-." in label:
467 raise EmailSyntaxError("An email address cannot have a period and a hyphen next to each other.")
468
469
470def uts46_valid_char(char: str) -> bool:
471 # By exhaustively searching for characters rejected by
472 # for c in (chr(i) for i in range(0x110000)):
473 # idna.uts46_remap(c, std3_rules=False, transitional=False)
474 # I found the following rules are pretty close.
475 c = ord(char)
476 if 0x80 <= c <= 0x9f:
477 # 8-bit ASCII range.
478 return False
479 elif ((0x2010 <= c <= 0x2060 and not (0x2024 <= c <= 0x2026) and not (0x2028 <= c <= 0x202E))
480 or c in (0x00AD, 0x2064, 0xFF0E)
481 or 0x200B <= c <= 0x200D
482 or 0x1BCA0 <= c <= 0x1BCA3):
483 # Characters that are permitted but fall into one of the
484 # tests below.
485 return True
486 elif unicodedata.category(chr(c)) in ("Cf", "Cn", "Co", "Cs", "Zs", "Zl", "Zp"):
487 # There are a bunch of Zs characters including regular space
488 # that are allowed by UTS46 but are not allowed in domain
489 # names anyway.
490 #
491 # There are some Cn (unassigned) characters that the idna
492 # package doesn't reject but we can, I think.
493 return False
494 elif "002E" in unicodedata.decomposition(chr(c)).split(" "):
495 # Characters that decompose into a sequence with a dot.
496 return False
497 return True
498
499
500class DomainNameValidationResult(TypedDict):
501 ascii_domain: str
502 domain: str
503
504
505def validate_email_domain_name(domain: str, test_environment: bool = False, globally_deliverable: bool = True) -> DomainNameValidationResult:
506 """Validates the syntax of the domain part of an email address."""
507
508 # A domain can get shorter through normalization (either from IDNA decoding or Unicode normalization),
509 # but the caller may use the original input, so the length check can apply up front. We also get a
510 # less helpful error via idna.uts46_remap and would rather do it ourselves. And it's important to
511 # prevent a DOS attack via idna: See below.
512 if len(domain) > DOMAIN_MAX_LENGTH:
513 reason = get_length_reason(domain, limit=DOMAIN_MAX_LENGTH)
514 raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.")
515
516 # Check for invalid characters.
517 # (RFC 952 plus RFC 6531 section 3.3 for internationalized addresses)
518 bad_chars = {
519 safe_character_display(c)
520 for c in domain
521 if not ATEXT_HOSTNAME_INTL.match(c)
522 }
523 if bad_chars:
524 raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
525
526 # Check for unsafe characters.
527 # Some of this may be redundant with the range U+0080 to U+10FFFF that is checked
528 # by DOT_ATOM_TEXT_INTL. Other characters may be permitted by the email specs, but
529 # they may not be valid, safe, or sensible Unicode strings.
530 check_unsafe_chars(domain)
531
532 # Reject characters that would be rejected by UTS-46 normalization next but
533 # with an error message under our control.
534 bad_chars = {
535 safe_character_display(c) for c in domain
536 if not uts46_valid_char(c)
537 }
538 if bad_chars:
539 raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
540
541 # Perform UTS-46 normalization, which includes casefolding, NFC normalization,
542 # and converting all label separators (the period/full stop, fullwidth full stop,
543 # ideographic full stop, and halfwidth ideographic full stop) to regular dots.
544 # It will also raise an exception if there is an invalid character in the input,
545 # such as "⒈" which is invalid because it would expand to include a dot and
546 # U+1FEF which normalizes to a backtick, which is not an allowed hostname character.
547 # Since several characters *are* normalized to a dot, this has to come before
548 # checks related to dots, like check_dot_atom which comes next.
549 original_domain = domain
550 try:
551 domain = idna.uts46_remap(domain, std3_rules=False, transitional=False)
552 except idna.IDNAError as e:
553 raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).") from e
554
555 # Check for invalid characters after Unicode normalization which are not caught
556 # by uts46_remap (see tests for examples).
557 bad_chars = {
558 safe_character_display(c)
559 for c in domain
560 if not ATEXT_HOSTNAME_INTL.match(c)
561 }
562 if bad_chars:
563 raise EmailSyntaxError("The part after the @-sign contains invalid characters after Unicode normalization: " + ", ".join(sorted(bad_chars)) + ".")
564
565 # The domain part is made up dot-separated "labels." Each label must
566 # have at least one character and cannot start or end with dashes, which
567 # means there are some surprising restrictions on periods and dashes.
568 # Check that before we do IDNA encoding because the IDNA library gives
569 # unfriendly errors for these cases, but after UTS-46 normalization because
570 # it can insert periods and hyphens (from fullwidth characters).
571 # (RFC 952, RFC 1123 2.1, RFC 5322 3.2.3)
572 check_dot_atom(domain, 'An email address cannot have a {} immediately after the @-sign.', 'An email address cannot end with a {}.', is_hostname=True)
573
574 # Check for RFC 5890's invalid R-LDH labels, which are labels that start
575 # with two characters other than "xn" and two dashes.
576 for label in domain.split("."):
577 if re.match(r"(?!xn)..--", label, re.I):
578 raise EmailSyntaxError("An email address cannot have two letters followed by two dashes immediately after the @-sign or after a period, except Punycode.")
579
580 if DOT_ATOM_TEXT_HOSTNAME.match(domain):
581 # This is a valid non-internationalized domain.
582 ascii_domain = domain
583 else:
584 # If international characters are present in the domain name, convert
585 # the domain to IDNA ASCII. If internationalized characters are present,
586 # the MTA must either support SMTPUTF8 or the mail client must convert the
587 # domain name to IDNA before submission.
588 #
589 # For ASCII-only domains, the transformation does nothing and is safe to
590 # apply. However, to ensure we don't rely on the idna library for basic
591 # syntax checks, we don't use it if it's not needed.
592 #
593 # idna.encode also checks the domain name length after encoding but it
594 # doesn't give a nice error, so we call the underlying idna.alabel method
595 # directly. idna.alabel checks label length and doesn't give great messages,
596 # but we can't easily go to lower level methods.
597 #
598 # idna.encode also rejects a domain that is too long before it looks
599 # at any label, because checking or decoding a long label can take time
600 # quadratic in its length (a long Punycode "xn--" label, or, before idna
601 # 3.15, a long run of Arabic-Indic digits). Since we call idna.alabel
602 # directly, check the length first above. A label never gets shorter
603 # when it is converted to IDNA ASCII, so a domain this long would fail
604 # the length check below anyway.
605 try:
606 ascii_domain = ".".join(
607 idna.alabel(label).decode("ascii")
608 for label in domain.split(".")
609 )
610 except idna.IDNAError as e:
611 # Some errors would have already been raised by idna.uts46_remap.
612 raise EmailSyntaxError(f"The part after the @-sign is invalid ({e}).") from e
613
614 # Check the syntax of the string returned by idna.encode.
615 # It should never fail.
616 if not DOT_ATOM_TEXT_HOSTNAME.match(ascii_domain):
617 raise EmailSyntaxError("The email address contains invalid characters after the @-sign after IDNA encoding.")
618
619 # Check the length of the domain name in bytes.
620 # (RFC 1035 2.3.4 and RFC 5321 4.5.3.1.2)
621 # We're checking the number of bytes ("octets") here, which can be much
622 # higher than the number of characters in internationalized domains,
623 # on the assumption that the domain may be transmitted without SMTPUTF8
624 # as IDNA ASCII. (This is also checked by idna.encode, so this exception
625 # is never reached for internationalized domains.)
626 if len(ascii_domain) > DOMAIN_MAX_LENGTH:
627 if ascii_domain == original_domain:
628 reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH)
629 raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.")
630 else:
631 diff = len(ascii_domain) - DOMAIN_MAX_LENGTH
632 s = "" if diff == 1 else "s"
633 raise EmailSyntaxError(f"The email address is too long after the @-sign ({diff} byte{s} too many after IDNA encoding).")
634
635 # Also check the label length limit.
636 # (RFC 1035 2.3.1)
637 for label in ascii_domain.split("."):
638 if len(label) > DNS_LABEL_LENGTH_LIMIT:
639 reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT)
640 raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.")
641
642 if globally_deliverable:
643 # All publicly deliverable addresses have domain names with at least
644 # one period, at least for gTLDs created since 2013 (per the ICANN Board
645 # New gTLD Program Committee, https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en).
646 # We'll consider the lack of a period a syntax error
647 # since that will match people's sense of what an email address looks
648 # like. We'll skip this in test environments to allow '@test' email
649 # addresses.
650 if "." not in ascii_domain and not (ascii_domain == "test" and test_environment):
651 raise EmailSyntaxError("The part after the @-sign is not valid. It should have a period.")
652
653 # We also know that all TLDs currently end with a letter.
654 if not DOMAIN_NAME_REGEX.search(ascii_domain):
655 raise EmailSyntaxError("The part after the @-sign is not valid. It is not within a valid top-level domain.")
656
657 # Check special-use and reserved domain names.
658 # Some might fail DNS-based deliverability checks, but that
659 # can be turned off, so we should fail them all sooner.
660 # See the references in __init__.py.
661 from . import SPECIAL_USE_DOMAIN_NAMES
662 for d in SPECIAL_USE_DOMAIN_NAMES:
663 # See the note near the definition of SPECIAL_USE_DOMAIN_NAMES.
664 if d == "test" and test_environment:
665 continue
666
667 if ascii_domain == d or ascii_domain.endswith("." + d):
668 raise EmailSyntaxError("The part after the @-sign is a special-use or reserved name that cannot be used with email.")
669
670 # Domains without Punycode labels come back unchanged from the IDNA round trip below.
671 if "xn--" not in ascii_domain:
672 return {
673 "ascii_domain": ascii_domain,
674 "domain": ascii_domain,
675 }
676
677 # We may have been given an IDNA ASCII domain to begin with. Check
678 # that the domain actually conforms to IDNA. It could look like IDNA
679 # but not be actual IDNA. For ASCII-only domains, the conversion out
680 # of IDNA just gives the same thing back.
681 #
682 # This gives us the canonical internationalized form of the domain,
683 # which we return to the caller as a part of the normalized email
684 # address.
685 try:
686 domain_i18n = idna.decode(ascii_domain.encode('ascii'))
687 except idna.IDNAError as e:
688 raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e
689
690 # Check that this normalized domain name has not somehow become
691 # an invalid domain name. All of the checks before this point
692 # using the idna package probably guarantee that we now have
693 # a valid international domain name in most respects. But it
694 # doesn't hurt to re-apply some tests to be sure. See the similar
695 # tests above.
696
697 # Check for invalid and unsafe characters. We have no test
698 # case for this.
699 bad_chars = {
700 safe_character_display(c)
701 for c in domain_i18n
702 if not ATEXT_HOSTNAME_INTL.match(c)
703 }
704 if bad_chars:
705 raise EmailSyntaxError("The part after the @-sign contains invalid characters: " + ", ".join(sorted(bad_chars)) + ".")
706 check_unsafe_chars(domain_i18n)
707
708 # If any label has right-to-left characters, the Bidi Rule applies to
709 # every label in the domain, including left-to-right ones (RFC 5893
710 # Section 1.4 and 2, UTS #46 CheckBidi). The idna package only checks
711 # each label on its own, so a label like "1" next to a right-to-left
712 # label was accepted, and such domains can be displayed identically to
713 # a different domain (e.g. 1.xn--4dbc.com and xn--4dbc.1.com, which
714 # are 1.אב.com and אב.1.com in Unicode, with Hebrew alef bet).
715 if any(unicodedata.bidirectional(c) in ("R", "AL", "AN") for c in domain_i18n):
716 for label in domain_i18n.split("."):
717 try:
718 idna.check_bidi(label, check_ltr=True)
719 except idna.IDNAError as e:
720 raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).") from e
721
722 # Check that it can be encoded back to IDNA ASCII. We have no test
723 # case for this.
724 try:
725 idna.encode(domain_i18n)
726 except idna.IDNAError as e:
727 raise EmailSyntaxError(f"The part after the @-sign became invalid after normalizing to international characters ({e}).") from e
728
729 # Return the IDNA ASCII-encoded form of the domain, which is how it
730 # would be transmitted on the wire (except when used with SMTPUTF8
731 # possibly), as well as the canonical Unicode form of the domain,
732 # which is better for display purposes. This should also take care
733 # of RFC 6532 section 3.1's suggestion to apply Unicode NFC
734 # normalization to addresses.
735 return {
736 "ascii_domain": ascii_domain,
737 "domain": domain_i18n,
738 }
739
740
741def validate_email_length(addrinfo: ValidatedEmail) -> None:
742 # There are three forms of the email address whose length must be checked:
743 #
744 # 1) The original email address string. Since callers may continue to use
745 # this string, even though we recommend using the normalized form, we
746 # should not pass validation when the original input is not valid. This
747 # form is checked first because it is the original input.
748 # 2) The normalized email address. We perform Unicode NFC normalization of
749 # the local part, we normalize the domain to internationalized characters
750 # (if originally IDNA ASCII) which also includes Unicode normalization,
751 # and we may remove quotes in quoted local parts. We recommend that
752 # callers use this string, so it must be valid.
753 # 3) The email address with the IDNA ASCII representation of the domain
754 # name, since this string may be used with email stacks that don't
755 # support UTF-8. Since this is the least likely to be used by callers,
756 # it is checked last. Note that ascii_email will only be set if the
757 # local part is ASCII, but conceivably the caller may combine a
758 # internationalized local part with an ASCII domain, so we check this
759 # on that combination also. Since we only return the normalized local
760 # part, we use that (and not the unnormalized local part).
761 #
762 # In all cases, the length is checked in UTF-8 because the SMTPUTF8
763 # extension to SMTP validates the length in bytes.
764
765 addresses_to_check = [
766 (addrinfo.original, None),
767 (addrinfo.normalized, "after normalization"),
768 ((addrinfo.ascii_local_part or addrinfo.local_part or "") + "@" + addrinfo.ascii_domain, "when the part after the @-sign is converted to IDNA ASCII"),
769 ]
770
771 for addr, reason in addresses_to_check:
772 addr_len = len(addr)
773 addr_utf8_len = len(addr.encode("utf8"))
774 diff = addr_utf8_len - EMAIL_MAX_LENGTH
775 if diff > 0:
776 if reason is None and addr_len == addr_utf8_len:
777 # If there is no normalization or transcoding,
778 # we can give a simple count of the number of
779 # characters over the limit.
780 reason = get_length_reason(addr, limit=EMAIL_MAX_LENGTH)
781 elif reason is None:
782 # If there is no normalization but there is
783 # some transcoding to UTF-8, we can compute
784 # the minimum number of characters over the
785 # limit by dividing the number of bytes over
786 # the limit by the maximum number of bytes
787 # per character.
788 mbpc = max(len(c.encode("utf8")) for c in addr)
789 mchars = max(1, diff // mbpc)
790 suffix = "s" if diff > 1 else ""
791 if mchars == diff:
792 reason = f"({diff} character{suffix} too many)"
793 else:
794 reason = f"({mchars}-{diff} character{suffix} too many)"
795 else:
796 # Since there is normalization, the number of
797 # characters in the input that need to change is
798 # impossible to know.
799 suffix = "s" if diff > 1 else ""
800 reason += f" ({diff} byte{suffix} too many)"
801 raise EmailSyntaxError(f"The email address is too long {reason}.")
802
803
804class DomainLiteralValidationResult(TypedDict):
805 domain_address: ipaddress.IPv4Address | ipaddress.IPv6Address
806 domain: str
807
808
809def validate_email_domain_literal(domain_literal: str) -> DomainLiteralValidationResult:
810 # This is obscure domain-literal syntax. Parse it and return
811 # a compressed/normalized address.
812 # RFC 5321 4.1.3 and RFC 5322 3.4.1.
813
814 addr: ipaddress.IPv4Address | ipaddress.IPv6Address
815
816 # Try to parse the domain literal as an IPv4 address.
817 # There is no tag for IPv4 addresses, so we can never
818 # be sure if the user intends an IPv4 address.
819 if re.match(r"^[0-9\.]+$", domain_literal):
820 try:
821 addr = ipaddress.IPv4Address(domain_literal)
822 except ValueError as e:
823 raise EmailSyntaxError(f"The address in brackets after the @-sign is not valid: It is not an IPv4 address ({e}) or is missing an address literal tag.") from e
824
825 # Return the IPv4Address object and the domain back unchanged.
826 return {
827 "domain_address": addr,
828 "domain": f"[{addr}]",
829 }
830
831 # If it begins with "IPv6:" it's an IPv6 address. The tag is case-insensitive
832 # like all ABNF literal strings (RFC 5234 2.3), so "ipv6:" is accepted too.
833 if domain_literal[:5].lower() == "ipv6:":
834 try:
835 addr = ipaddress.IPv6Address(domain_literal[5:])
836 except ValueError as e:
837 raise EmailSyntaxError(f"The IPv6 address in brackets after the @-sign is not valid ({e}).") from e
838
839 # Python accepts a zone index ("%eth0") but RFC 5321 4.1.3 does not.
840 if addr.scope_id is not None:
841 raise EmailSyntaxError("The IPv6 address in brackets after the @-sign is not valid (It has a zone index).")
842
843 # Return the IPv6Address object and construct a normalized
844 # domain literal.
845 return {
846 "domain_address": addr,
847 "domain": f"[IPv6:{addr.compressed}]",
848 }
849
850 # Nothing else is valid.
851
852 if ":" not in domain_literal:
853 raise EmailSyntaxError("The part after the @-sign in brackets is not an IPv4 address and has no address literal tag.")
854
855 # The tag (the part before the colon) has character restrictions,
856 # but since it must come from a registry of tags (in which only "IPv6" is defined),
857 # there's no need to check the syntax of the tag. See RFC 5321 4.1.2.
858
859 # Check for permitted ASCII characters. This actually doesn't matter
860 # since there will be an exception after anyway.
861 bad_chars = {
862 safe_character_display(c)
863 for c in domain_literal
864 if not DOMAIN_LITERAL_CHARS.match(c)
865 }
866 if bad_chars:
867 raise EmailSyntaxError("The part after the @-sign contains invalid characters in brackets: " + ", ".join(sorted(bad_chars)) + ".")
868
869 # There are no other domain literal tags.
870 # https://www.iana.org/assignments/address-literal-tags/address-literal-tags.xhtml
871 raise EmailSyntaxError("The part after the @-sign contains an invalid address literal tag in brackets.")