9 "github.com/mjl-/mox/dns"
12// Pedantic enables stricter parsing.
15var ErrBadAddress = errors.New("invalid email address")
17// Localpart is a decoded local part of an email address, before the "@".
18// For quoted strings, values do not hold the double quote or escaping backslashes.
19// An empty string can be a valid localpart.
22// String returns a packed representation of an address, with proper escaping/quoting, for use in SMTP.
23func (lp Localpart) String() string {
25 // First we try as dot-string. If not possible we make a quoted-string.
27 t := strings.Split(string(lp), ".")
30 if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c > 0x7f {
34 case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~':
40 dotstr = dotstr && len(e) > 0
42 dotstr = dotstr && len(t) > 0
47 // Make quoted-string.
49 for _, b := range lp {
50 if b == '"' || b == '\\' {
60// LogString returns the localpart as string for use in smtp, and an escaped
61// representation if it has non-ascii characters.
62func (lp Localpart) LogString() string {
64 qs := strconv.QuoteToASCII(s)
71// DSNString returns the localpart as string for use in a DSN.
72// utf8 indicates if the remote MTA supports utf8 messaging. If not, the 7bit DSN
73// encoding for "utf-8-addr-xtext" from RFC 6533 is used.
74func (lp Localpart) DSNString(utf8 bool) string {
80 for _, c := range lp {
81 if c > 0x20 && c < 0x7f && c != '\\' && c != '+' && c != '=' {
84 r += fmt.Sprintf(`\x{%x}`, c)
90// IsInternational returns if this is an internationalized local part, i.e. has
91// non-ASCII characters.
92func (lp Localpart) IsInternational() bool {
93 for _, c := range lp {
101// Address is a parsed email address.
104 Domain dns.Domain // todo: shouldn't we accept an ip address here too? and merge this type into smtp.Path.
107// NewAddress returns an address.
108func NewAddress(localpart Localpart, domain dns.Domain) Address {
109 return Address{localpart, domain}
112func (a Address) Path() Path {
113 return Path{Localpart: a.Localpart, IPDomain: dns.IPDomain{Domain: a.Domain}}
116func (a Address) IsZero() bool {
117 return a == Address{}
120// Pack returns the address in string form. If smtputf8 is true, the domain is
121// formatted with non-ASCII characters. If localpart has non-ASCII characters,
122// they are returned regardless of smtputf8.
123func (a Address) Pack(smtputf8 bool) string {
127 return a.Localpart.String() + "@" + a.Domain.XName(smtputf8)
130// String returns the address in string form with non-ASCII characters.
131func (a Address) String() string {
135 return a.Localpart.String() + "@" + a.Domain.Name()
138// LogString returns the address with with utf-8 in localpart and/or domain. In
139// case of an IDNA domain and/or quotable characters in the localpart, an address
140// with quoted/escaped localpart and ASCII domain is also returned.
141func (a Address) LogString() string {
146 lp := a.Localpart.String()
147 qlp := strconv.QuoteToASCII(lp)
148 escaped := qlp != `"`+lp+`"`
149 if a.Domain.Unicode != "" || escaped {
153 s += "/" + lp + "@" + a.Domain.ASCII
158// ParseAddress parses an email address. UTF-8 is allowed.
159// Returns ErrBadAddress for invalid addresses.
160func ParseAddress(s string) (address Address, err error) {
161 lp, rem, err := parseLocalPart(s)
163 return Address{}, fmt.Errorf("%w: %s", ErrBadAddress, err)
165 if !strings.HasPrefix(rem, "@") {
166 return Address{}, fmt.Errorf("%w: expected @", ErrBadAddress)
169 d, err := dns.ParseDomain(rem)
171 return Address{}, fmt.Errorf("%w: %s", ErrBadAddress, err)
173 return Address{lp, d}, err
176var ErrBadLocalpart = errors.New("invalid localpart")
178// ParseLocalpart parses the local part.
180// Returns ErrBadAddress for invalid addresses.
181func ParseLocalpart(s string) (localpart Localpart, err error) {
182 lp, rem, err := parseLocalPart(s)
187 return "", fmt.Errorf("%w: remaining after localpart: %q", ErrBadLocalpart, rem)
192func parseLocalPart(s string) (localpart Localpart, remain string, err error) {
204 err = fmt.Errorf("%w: %s", ErrBadLocalpart, e)
208 return lp, p.remainder(), nil
216func (p *parser) xerrorf(format string, args ...any) {
217 panic(fmt.Errorf(format, args...))
220func (p *parser) hasPrefix(s string) bool {
221 return strings.HasPrefix(p.s[p.o:], s)
224func (p *parser) take(s string) bool {
232func (p *parser) xtake(s string) {
234 p.xerrorf("expected %q", s)
238func (p *parser) empty() bool {
239 return p.o == len(p.s)
242func (p *parser) xtaken(n int) string {
243 r := p.s[p.o : p.o+n]
248func (p *parser) remainder() string {
254// todo: reduce duplication between implementations: ../smtp/address.go:/xlocalpart ../dkim/parser.go:/xlocalpart ../smtpserver/parse.go:/xlocalpart
255func (p *parser) xlocalpart() Localpart {
258 if p.hasPrefix(`"`) {
259 s = p.xquotedString()
266 // In the wild, some services use large localparts for generated (bounce) addresses.
267 if Pedantic && len(s) > 64 || len(s) > 128 {
269 p.xerrorf("localpart longer than 64 octets")
274func (p *parser) xquotedString() string {
281 if c >= ' ' && c < 0x7f {
286 p.xerrorf("invalid localpart, bad escaped char %c", c)
295 // todo: should we be accepting utf8 for quoted strings?
296 if c >= ' ' && c < 0x7f && c != '\\' && c != '"' || c > 0x7f {
300 p.xerrorf("invalid localpart, invalid character %c", c)
304func (p *parser) xchar() rune {
305 // We are careful to track invalid utf-8 properly.
307 p.xerrorf("need another character")
311 for i, c := range p.s[p.o:] {
326func (p *parser) takefn1(what string, fn func(c rune, i int) bool) string {
328 p.xerrorf("need at least one char for %s", what)
330 for i, c := range p.s[p.o:] {
333 p.xerrorf("expected at least one char for %s, got char %c", what, c)
341func (p *parser) xatom() string {
342 return p.takefn1("atom", func(c rune, i int) bool {
344 case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~':
347 return isalphadigit(c) || c > 0x7f
351func isalpha(c rune) bool {
352 return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
355func isdigit(c rune) bool {
356 return c >= '0' && c <= '9'
359func isalphadigit(c rune) bool {
360 return isalpha(c) || isdigit(c)