9 "golang.org/x/text/unicode/norm"
11 "github.com/mjl-/mox/dns"
14// Pedantic enables stricter parsing.
17var ErrBadAddress = errors.New("invalid email address")
19// Localpart is a decoded local part of an email address, before the "@".
20// For quoted strings, values do not hold the double quote or escaping backslashes.
21// An empty string can be a valid localpart.
22// Localparts are in Unicode NFC.
25// String returns a packed representation of an address, with proper escaping/quoting, for use in SMTP.
26func (lp Localpart) String() string {
28 // First we try as dot-string. If not possible we make a quoted-string.
30 t := strings.Split(string(lp), ".")
33 if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c > 0x7f {
37 case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~':
43 dotstr = dotstr && len(e) > 0
45 dotstr = dotstr && len(t) > 0
50 // Make quoted-string.
53 for _, b := range lp {
54 if b == '"' || b == '\\' {
55 r.WriteString("\\" + string(b))
57 r.WriteString(string(b))
64// LogString returns the localpart as string for use in smtp, and an escaped
65// representation if it has non-ascii characters.
66func (lp Localpart) LogString() string {
68 qs := strconv.QuoteToASCII(s)
75// DSNString returns the localpart as string for use in a DSN.
76// utf8 indicates if the remote MTA supports utf8 messaging. If not, the 7bit DSN
77// encoding for "utf-8-addr-xtext" from RFC 6533 is used.
78func (lp Localpart) DSNString(utf8 bool) string {
84 for _, c := range lp {
85 if c > 0x20 && c < 0x7f && c != '\\' && c != '+' && c != '=' {
86 r.WriteString(string(c))
88 r.WriteString(fmt.Sprintf(`\x{%x}`, c))
94// IsInternational returns if this is an internationalized local part, i.e. has
95// non-ASCII characters.
96func (lp Localpart) IsInternational() bool {
97 for _, c := range lp {
105// Address is a parsed email address.
108 Domain dns.Domain // todo: shouldn't we accept an ip address here too? and merge this type into smtp.Path.
111// NewAddress returns an address.
112func NewAddress(localpart Localpart, domain dns.Domain) Address {
113 return Address{localpart, domain}
116func (a Address) Path() Path {
117 return Path{Localpart: a.Localpart, IPDomain: dns.IPDomain{Domain: a.Domain}}
120func (a Address) IsZero() bool {
121 return a == Address{}
124// Pack returns the address in string form. If smtputf8 is true, the domain is
125// formatted with non-ASCII characters. If localpart has non-ASCII characters,
126// they are returned regardless of smtputf8.
127func (a Address) Pack(smtputf8 bool) string {
131 return a.Localpart.String() + "@" + a.Domain.XName(smtputf8)
134// String returns the address in string form with non-ASCII characters.
135func (a Address) String() string {
139 return a.Localpart.String() + "@" + a.Domain.Name()
142// LogString returns the address with with utf-8 in localpart and/or domain. In
143// case of an IDNA domain and/or quotable characters in the localpart, an address
144// with quoted/escaped localpart and ASCII domain is also returned.
145func (a Address) LogString() string {
150 lp := a.Localpart.String()
151 qlp := strconv.QuoteToASCII(lp)
152 escaped := qlp != `"`+lp+`"`
153 if a.Domain.Unicode != "" || escaped {
157 s += "/" + lp + "@" + a.Domain.ASCII
162// ParseAddress parses an email address. UTF-8 is allowed.
163// Returns ErrBadAddress for invalid addresses.
164func ParseAddress(s string) (address Address, err error) {
165 lp, rem, err := parseLocalPart(s)
167 return Address{}, fmt.Errorf("%w: %s", ErrBadAddress, err)
169 if !strings.HasPrefix(rem, "@") {
170 return Address{}, fmt.Errorf("%w: expected @", ErrBadAddress)
173 d, err := dns.ParseDomain(rem)
175 return Address{}, fmt.Errorf("%w: %s", ErrBadAddress, err)
177 return Address{lp, d}, err
180// ParseNetMailAddress parses a not-quite-valid address as found in
181// net/mail.Address.Address.
183// net/mail does parse quoted addresses properly, but stores the localpart
184// unquoted. So an address `" "@example.com` would be stored as ` @example.com`,
185// which we would fail to parse without special attention.
186func ParseNetMailAddress(a string) (address Address, err error) {
187 i := strings.LastIndex(a, "@")
189 return Address{}, fmt.Errorf("%w: missing @", ErrBadAddress)
191 addrStr := Localpart(a[:i]).String() + "@" + a[i+1:]
192 return ParseAddress(addrStr)
195var ErrBadLocalpart = errors.New("invalid localpart")
197// ParseLocalpart parses the local part.
199// Returns ErrBadAddress for invalid addresses.
200func ParseLocalpart(s string) (localpart Localpart, err error) {
201 lp, rem, err := parseLocalPart(s)
206 return "", fmt.Errorf("%w: remaining after localpart: %q", ErrBadLocalpart, rem)
211func parseLocalPart(s string) (localpart Localpart, remain string, err error) {
223 err = fmt.Errorf("%w: %s", ErrBadLocalpart, e)
227 return lp, p.remainder(), nil
235func (p *parser) xerrorf(format string, args ...any) {
236 panic(fmt.Errorf(format, args...))
239func (p *parser) hasPrefix(s string) bool {
240 return strings.HasPrefix(p.s[p.o:], s)
243func (p *parser) take(s string) bool {
251func (p *parser) xtake(s string) {
253 p.xerrorf("expected %q", s)
257func (p *parser) empty() bool {
258 return p.o == len(p.s)
261func (p *parser) xtaken(n int) string {
262 r := p.s[p.o : p.o+n]
267func (p *parser) remainder() string {
273// todo: reduce duplication between implementations: ../smtp/address.go:/xlocalpart ../dkim/parser.go:/xlocalpart ../smtpserver/parse.go:/xlocalpart
274func (p *parser) xlocalpart() Localpart {
277 if p.hasPrefix(`"`) {
278 s = p.xquotedString()
285 // In the wild, some services use large localparts for generated (bounce) addresses.
286 if Pedantic && len(s) > 64 || len(s) > 128 {
288 p.xerrorf("localpart longer than 64 octets")
290 return Localpart(norm.NFC.String(s))
293func (p *parser) xquotedString() string {
300 if c >= ' ' && c < 0x7f {
305 p.xerrorf("invalid localpart, bad escaped char %c", c)
314 // todo: should we be accepting utf8 for quoted strings?
315 if c >= ' ' && c < 0x7f && c != '\\' && c != '"' || c > 0x7f {
319 p.xerrorf("invalid localpart, invalid character %c", c)
323func (p *parser) xchar() rune {
324 // We are careful to track invalid utf-8 properly.
326 p.xerrorf("need another character")
330 for i, c := range p.s[p.o:] {
345func (p *parser) takefn1(what string, fn func(c rune, i int) bool) string {
347 p.xerrorf("need at least one char for %s", what)
349 for i, c := range p.s[p.o:] {
352 p.xerrorf("expected at least one char for %s, got char %c", what, c)
360func (p *parser) xatom() string {
361 return p.takefn1("atom", func(c rune, i int) bool {
363 case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~':
366 return isalphadigit(c) || c > 0x7f
370func isalpha(c rune) bool {
371 return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
374func isdigit(c rune) bool {
375 return c >= '0' && c <= '9'
378func isalphadigit(c rune) bool {
379 return isalpha(c) || isdigit(c)