1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
6 Package mail implements parsing of mail messages.
8 For the most part, this package follows the syntax as specified by RFC 5322.
10 * Obsolete address formats are not parsed, including addresses with
11 embedded route information.
12 * Group addresses are not parsed.
13 * The full range of spacing (the CFWS syntax element) is not supported,
14 such as breaking addresses across lines.
33 var debug = debugT(false)
37 func (d debugT) Printf(format string, args ...interface{}) {
39 log.Printf(format, args...)
43 // A Message represents a parsed mail message.
49 // ReadMessage reads a message from r.
50 // The headers are parsed, and the body of the message will be available
51 // for reading from r.
52 func ReadMessage(r io.Reader) (msg *Message, err error) {
53 tp := textproto.NewReader(bufio.NewReader(r))
55 hdr, err := tp.ReadMIMEHeader()
66 // Layouts suitable for passing to time.Parse.
67 // These are tried in order.
68 var dateLayouts []string
71 // Generate layouts based on RFC 5322, section 3.3.
73 dows := [...]string{"", "Mon, "} // day-of-week
74 days := [...]string{"2", "02"} // day = 1*2DIGIT
75 years := [...]string{"2006", "06"} // year = 4*DIGIT / 2*DIGIT
76 seconds := [...]string{":05", ""} // second
77 // "-0700 (MST)" is not in RFC 5322, but is common.
78 zones := [...]string{"-0700", "MST", "-0700 (MST)"} // zone = (("+" / "-") 4DIGIT) / "GMT" / ...
80 for _, dow := range dows {
81 for _, day := range days {
82 for _, year := range years {
83 for _, second := range seconds {
84 for _, zone := range zones {
85 s := dow + day + " Jan " + year + " 15:04" + second + " " + zone
86 dateLayouts = append(dateLayouts, s)
94 func parseDate(date string) (time.Time, error) {
95 for _, layout := range dateLayouts {
96 t, err := time.Parse(layout, date)
101 return time.Time{}, errors.New("mail: header could not be parsed")
104 // A Header represents the key-value pairs in a mail message header.
105 type Header map[string][]string
107 // Get gets the first value associated with the given key.
108 // If there are no values associated with the key, Get returns "".
109 func (h Header) Get(key string) string {
110 return textproto.MIMEHeader(h).Get(key)
113 var ErrHeaderNotPresent = errors.New("mail: header not in message")
115 // Date parses the Date header field.
116 func (h Header) Date() (time.Time, error) {
119 return time.Time{}, ErrHeaderNotPresent
121 return parseDate(hdr)
124 // AddressList parses the named header field as a list of addresses.
125 func (h Header) AddressList(key string) ([]*Address, error) {
128 return nil, ErrHeaderNotPresent
130 return newAddrParser(hdr).parseAddressList()
133 // Address represents a single mail address.
134 // An address such as "Barry Gibbs <bg@example.com>" is represented
135 // as Address{Name: "Barry Gibbs", Address: "bg@example.com"}.
136 type Address struct {
137 Name string // Proper name; may be empty.
138 Address string // user@domain
141 // String formats the address as a valid RFC 5322 address.
142 // If the address's name contains non-ASCII characters
143 // the name will be rendered according to RFC 2047.
144 func (a *Address) String() string {
145 s := "<" + a.Address + ">"
149 // If every character is printable ASCII, quoting is simple.
151 for i := 0; i < len(a.Name); i++ {
152 if !isVchar(a.Name[i]) {
158 b := bytes.NewBufferString(`"`)
159 for i := 0; i < len(a.Name); i++ {
160 if !isQtext(a.Name[i]) {
163 b.WriteByte(a.Name[i])
170 // UTF-8 "Q" encoding
171 b := bytes.NewBufferString("=?utf-8?q?")
172 for i := 0; i < len(a.Name); i++ {
173 switch c := a.Name[i]; {
176 case isVchar(c) && c != '=' && c != '?' && c != '_':
179 fmt.Fprintf(b, "=%02X", c)
187 type addrParser []byte
189 func newAddrParser(s string) *addrParser {
194 func (p *addrParser) parseAddressList() ([]*Address, error) {
198 addr, err := p.parseAddress()
202 list = append(list, addr)
209 return nil, errors.New("mail: expected comma")
215 // parseAddress parses a single RFC 5322 address at the start of p.
216 func (p *addrParser) parseAddress() (addr *Address, err error) {
217 debug.Printf("parseAddress: %q", *p)
220 return nil, errors.New("mail: no address")
223 // address = name-addr / addr-spec
224 // TODO(dsymonds): Support parsing group address.
226 // addr-spec has a more restricted grammar than name-addr,
227 // so try parsing it first, and fallback to name-addr.
228 // TODO(dsymonds): Is this really correct?
229 spec, err := p.consumeAddrSpec()
235 debug.Printf("parseAddress: not an addr-spec: %v", err)
236 debug.Printf("parseAddress: state is now %q", *p)
239 var displayName string
241 displayName, err = p.consumePhrase()
246 debug.Printf("parseAddress: displayName=%q", displayName)
248 // angle-addr = "<" addr-spec ">"
251 return nil, errors.New("mail: no angle-addr")
253 spec, err = p.consumeAddrSpec()
258 return nil, errors.New("mail: unclosed angle-addr")
260 debug.Printf("parseAddress: spec=%q", spec)
268 // consumeAddrSpec parses a single RFC 5322 addr-spec at the start of p.
269 func (p *addrParser) consumeAddrSpec() (spec string, err error) {
270 debug.Printf("consumeAddrSpec: %q", *p)
279 // local-part = dot-atom / quoted-string
283 return "", errors.New("mail: no addr-spec")
287 debug.Printf("consumeAddrSpec: parsing quoted-string")
288 localPart, err = p.consumeQuotedString()
291 debug.Printf("consumeAddrSpec: parsing dot-atom")
292 localPart, err = p.consumeAtom(true)
295 debug.Printf("consumeAddrSpec: failed: %v", err)
300 return "", errors.New("mail: missing @ in addr-spec")
303 // domain = dot-atom / domain-literal
307 return "", errors.New("mail: no domain in addr-spec")
309 // TODO(dsymonds): Handle domain-literal
310 domain, err = p.consumeAtom(true)
315 return localPart + "@" + domain, nil
318 // consumePhrase parses the RFC 5322 phrase at the start of p.
319 func (p *addrParser) consumePhrase() (phrase string, err error) {
320 debug.Printf("consumePhrase: [%s]", *p)
324 // word = atom / quoted-string
328 return "", errors.New("mail: missing phrase")
332 word, err = p.consumeQuotedString()
335 word, err = p.consumeAtom(false)
338 // RFC 2047 encoded-word starts with =?, ends with ?=, and has two other ?s.
339 if err == nil && strings.HasPrefix(word, "=?") && strings.HasSuffix(word, "?=") && strings.Count(word, "?") == 4 {
340 word, err = decodeRFC2047Word(word)
346 debug.Printf("consumePhrase: consumed %q", word)
347 words = append(words, word)
349 // Ignore any error if we got at least one word.
350 if err != nil && len(words) == 0 {
351 debug.Printf("consumePhrase: hit err: %v", err)
352 return "", errors.New("mail: missing word in phrase")
354 phrase = strings.Join(words, " ")
358 // consumeQuotedString parses the quoted string at the start of p.
359 func (p *addrParser) consumeQuotedString() (qs string, err error) {
360 // Assume first byte is '"'.
362 qsb := make([]byte, 0, 10)
366 return "", errors.New("mail: unclosed quoted-string")
368 switch c := (*p)[i]; {
373 return "", errors.New("mail: unclosed quoted-string")
375 qsb = append(qsb, (*p)[i+1])
377 case isQtext(c), c == ' ' || c == '\t':
378 // qtext (printable US-ASCII excluding " and \), or
379 // FWS (almost; we're ignoring CRLF)
383 return "", fmt.Errorf("mail: bad character in quoted-string: %q", c)
387 return string(qsb), nil
390 // consumeAtom parses an RFC 5322 atom at the start of p.
391 // If dot is true, consumeAtom parses an RFC 5322 dot-atom instead.
392 func (p *addrParser) consumeAtom(dot bool) (atom string, err error) {
393 if !isAtext(p.peek(), false) {
394 return "", errors.New("mail: invalid string")
397 for ; i < p.len() && isAtext((*p)[i], dot); i++ {
399 atom, *p = string((*p)[:i]), (*p)[i:]
403 func (p *addrParser) consume(c byte) bool {
404 if p.empty() || p.peek() != c {
411 // skipSpace skips the leading space and tab characters.
412 func (p *addrParser) skipSpace() {
413 *p = bytes.TrimLeft(*p, " \t")
416 func (p *addrParser) peek() byte {
420 func (p *addrParser) empty() bool {
424 func (p *addrParser) len() int {
428 func decodeRFC2047Word(s string) (string, error) {
429 fields := strings.Split(s, "?")
430 if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" {
431 return "", errors.New("mail: address not RFC 2047 encoded")
433 charset, enc := strings.ToLower(fields[1]), strings.ToLower(fields[2])
434 if charset != "iso-8859-1" && charset != "utf-8" {
435 return "", fmt.Errorf("mail: charset not supported: %q", charset)
438 in := bytes.NewBufferString(fields[3])
442 r = base64.NewDecoder(base64.StdEncoding, in)
446 return "", fmt.Errorf("mail: RFC 2047 encoding not supported: %q", enc)
449 dec, err := ioutil.ReadAll(r)
456 b := new(bytes.Buffer)
457 for _, c := range dec {
460 return b.String(), nil
462 return string(dec), nil
467 type qDecoder struct {
472 func (qd qDecoder) Read(p []byte) (n int, err error) {
473 // This method writes at most one byte into p.
477 if _, err := qd.r.Read(qd.scratch[:1]); err != nil {
480 switch c := qd.scratch[0]; {
482 if _, err := io.ReadFull(qd.r, qd.scratch[:2]); err != nil {
485 x, err := strconv.ParseInt(string(qd.scratch[:2]), 16, 64)
487 return 0, fmt.Errorf("mail: invalid RFC 2047 encoding: %q", qd.scratch[:2])
498 var atextChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
499 "abcdefghijklmnopqrstuvwxyz" +
501 "!#$%&'*+-/=?^_`{|}~")
503 // isAtext returns true if c is an RFC 5322 atext character.
504 // If dot is true, period is included.
505 func isAtext(c byte, dot bool) bool {
509 return bytes.IndexByte(atextChars, c) >= 0
512 // isQtext returns true if c is an RFC 5322 qtest character.
513 func isQtext(c byte) bool {
514 // Printable US-ASCII, excluding backslash or quote.
515 if c == '\\' || c == '"' {
518 return '!' <= c && c <= '~'
521 // isVchar returns true if c is an RFC 5322 VCHAR character.
522 func isVchar(c byte) bool {
523 // Visible (printing) characters.
524 return '!' <= c && c <= '~'