encode method

String encode()

Encodes this mail address

A personal name of printable ASCII characters is rendered as an RFC 5322 quoted-string, escaping " and \. Any other personal name is rendered as RFC 2047 encoded-words that replace the phrase, since an encoded-word must not appear inside a quoted-string (section 5). Throws an ArgumentError when email contains characters that would break the address header, compare isSafeEmail.

Compare MailAddress.parse to decode an address

Implementation

String encode() {
  if (!isSafeEmail(email)) {
    throw ArgumentError.value(
      email,
      'email',
      'contains characters that are not allowed in an address header',
    );
  }
  final personalName = this.personalName;
  if (personalName == null || hasNoPersonalName) {
    return email;
  }
  final name = personalName.trim();
  if (!_isPrintableAscii(name)) {
    final encoded = MailCodec.quotedPrintable.encodeHeader(
      name,
      isPhrase: true,
    );

    return '$encoded <$email>';
  }
  // RFC 5322 section 3.2.4: within a quoted-string the characters " and \
  // have to be escaped as quoted-pairs
  final quoted = name.replaceAll(r'\', r'\\').replaceAll('"', r'\"');

  return '"$quoted" <$email>';
}