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 reading from r.
51 func ReadMessage(r io.Reader) (msg *Message, err error) {
52 tp := textproto.NewReader(bufio.NewReader(r))
54 hdr, err := tp.ReadMIMEHeader()
65 // Layouts suitable for passing to time.Parse.
66 // These are tried in order.
67 var dateLayouts []string
70 // Generate layouts based on RFC 5322, section 3.3.
72 dows := [...]string{"", "Mon, "} // day-of-week
73 days := [...]string{"2", "02"} // day = 1*2DIGIT
74 years := [...]string{"2006", "06"} // year = 4*DIGIT / 2*DIGIT
75 seconds := [...]string{":05", ""} // second
76 zones := [...]string{"-0700", "MST"} // zone = (("+" / "-") 4DIGIT) / "GMT" / ...
78 for _, dow := range dows {
79 for _, day := range days {
80 for _, year := range years {
81 for _, second := range seconds {
82 for _, zone := range zones {
83 s := dow + day + " Jan " + year + " 15:04" + second + " " + zone
84 dateLayouts = append(dateLayouts, s)
92 func parseDate(date string) (time.Time, error) {
93 for _, layout := range dateLayouts {
94 t, err := time.Parse(layout, date)
99 return time.Time{}, errors.New("mail: header could not be parsed")
102 // A Header represents the key-value pairs in a mail message header.
103 type Header map[string][]string
105 // Get gets the first value associated with the given key.
106 // If there are no values associated with the key, Get returns "".
107 func (h Header) Get(key string) string {
108 return textproto.MIMEHeader(h).Get(key)
111 var ErrHeaderNotPresent = errors.New("mail: header not in message")
113 // Date parses the Date header field.
114 func (h Header) Date() (time.Time, error) {
117 return time.Time{}, ErrHeaderNotPresent
119 return parseDate(hdr)
122 // AddressList parses the named header field as a list of addresses.
123 func (h Header) AddressList(key string) ([]*Address, error) {
126 return nil, ErrHeaderNotPresent
128 return newAddrParser(hdr).parseAddressList()
131 // Address represents a single mail address.
132 // An address such as "Barry Gibbs <bg@example.com>" is represented
133 // as Address{Name: "Barry Gibbs", Address: "bg@example.com"}.
134 type Address struct {
135 Name string // Proper name; may be empty.
136 Address string // user@domain
139 // String formats the address as a valid RFC 5322 address.
140 // If the address's name contains non-ASCII characters
141 // the name will be rendered according to RFC 2047.
142 func (a *Address) String() string {
143 s := "<" + a.Address + ">"
147 // If every character is printable ASCII, quoting is simple.
149 for i := 0; i < len(a.Name); i++ {
150 if !isVchar(a.Name[i]) {
156 b := bytes.NewBufferString(`"`)
157 for i := 0; i < len(a.Name); i++ {
158 if !isQtext(a.Name[i]) {
161 b.WriteByte(a.Name[i])
168 // UTF-8 "Q" encoding
169 b := bytes.NewBufferString("=?utf-8?q?")
170 for i := 0; i < len(a.Name); i++ {
171 switch c := a.Name[i]; {
174 case isVchar(c) && c != '=' && c != '?' && c != '_':
177 fmt.Fprintf(b, "=%02X", c)
185 type addrParser []byte
187 func newAddrParser(s string) *addrParser {
192 func (p *addrParser) parseAddressList() ([]*Address, error) {
196 addr, err := p.parseAddress()
200 list = append(list, addr)
207 return nil, errors.New("mail: expected comma")
213 // parseAddress parses a single RFC 5322 address at the start of p.
214 func (p *addrParser) parseAddress() (addr *Address, err error) {
215 debug.Printf("parseAddress: %q", *p)
218 return nil, errors.New("mail: no address")
221 // address = name-addr / addr-spec
222 // TODO(dsymonds): Support parsing group address.
224 // addr-spec has a more restricted grammar than name-addr,
225 // so try parsing it first, and fallback to name-addr.
226 // TODO(dsymonds): Is this really correct?
227 spec, err := p.consumeAddrSpec()
233 debug.Printf("parseAddress: not an addr-spec: %v", err)
234 debug.Printf("parseAddress: state is now %q", *p)
237 var displayName string
239 displayName, err = p.consumePhrase()
244 debug.Printf("parseAddress: displayName=%q", displayName)
246 // angle-addr = "<" addr-spec ">"
249 return nil, errors.New("mail: no angle-addr")
251 spec, err = p.consumeAddrSpec()
256 return nil, errors.New("mail: unclosed angle-addr")
258 debug.Printf("parseAddress: spec=%q", spec)
266 // consumeAddrSpec parses a single RFC 5322 addr-spec at the start of p.
267 func (p *addrParser) consumeAddrSpec() (spec string, err error) {
268 debug.Printf("consumeAddrSpec: %q", *p)
277 // local-part = dot-atom / quoted-string
281 return "", errors.New("mail: no addr-spec")
285 debug.Printf("consumeAddrSpec: parsing quoted-string")
286 localPart, err = p.consumeQuotedString()
289 debug.Printf("consumeAddrSpec: parsing dot-atom")
290 localPart, err = p.consumeAtom(true)
293 debug.Printf("consumeAddrSpec: failed: %v", err)
298 return "", errors.New("mail: missing @ in addr-spec")
301 // domain = dot-atom / domain-literal
305 return "", errors.New("mail: no domain in addr-spec")
307 // TODO(dsymonds): Handle domain-literal
308 domain, err = p.consumeAtom(true)
313 return localPart + "@" + domain, nil
316 // consumePhrase parses the RFC 5322 phrase at the start of p.
317 func (p *addrParser) consumePhrase() (phrase string, err error) {
318 debug.Printf("consumePhrase: [%s]", *p)
322 // word = atom / quoted-string
326 return "", errors.New("mail: missing phrase")
330 word, err = p.consumeQuotedString()
333 word, err = p.consumeAtom(false)
336 // RFC 2047 encoded-word starts with =?, ends with ?=, and has two other ?s.
337 if err == nil && strings.HasPrefix(word, "=?") && strings.HasSuffix(word, "?=") && strings.Count(word, "?") == 4 {
338 word, err = decodeRFC2047Word(word)
344 debug.Printf("consumePhrase: consumed %q", word)
345 words = append(words, word)
347 // Ignore any error if we got at least one word.
348 if err != nil && len(words) == 0 {
349 debug.Printf("consumePhrase: hit err: %v", err)
350 return "", errors.New("mail: missing word in phrase")
352 phrase = strings.Join(words, " ")
356 // consumeQuotedString parses the quoted string at the start of p.
357 func (p *addrParser) consumeQuotedString() (qs string, err error) {
358 // Assume first byte is '"'.
360 qsb := make([]byte, 0, 10)
364 return "", errors.New("mail: unclosed quoted-string")
366 switch c := (*p)[i]; {
371 return "", errors.New("mail: unclosed quoted-string")
373 qsb = append(qsb, (*p)[i+1])
375 case isQtext(c), c == ' ' || c == '\t':
376 // qtext (printable US-ASCII excluding " and \), or
377 // FWS (almost; we're ignoring CRLF)
381 return "", fmt.Errorf("mail: bad character in quoted-string: %q", c)
385 return string(qsb), nil
388 // consumeAtom parses an RFC 5322 atom at the start of p.
389 // If dot is true, consumeAtom parses an RFC 5322 dot-atom instead.
390 func (p *addrParser) consumeAtom(dot bool) (atom string, err error) {
391 if !isAtext(p.peek(), false) {
392 return "", errors.New("mail: invalid string")
395 for ; i < p.len() && isAtext((*p)[i], dot); i++ {
397 // TODO(dsymonds): Remove the []byte() conversion here when 6g doesn't need it.
398 atom, *p = string([]byte((*p)[:i])), (*p)[i:]
402 func (p *addrParser) consume(c byte) bool {
403 if p.empty() || p.peek() != c {
410 // skipSpace skips the leading space and tab characters.
411 func (p *addrParser) skipSpace() {
412 *p = bytes.TrimLeft(*p, " \t")
415 func (p *addrParser) peek() byte {
419 func (p *addrParser) empty() bool {
423 func (p *addrParser) len() int {
427 func decodeRFC2047Word(s string) (string, error) {
428 fields := strings.Split(s, "?")
429 if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" {
430 return "", errors.New("mail: address not RFC 2047 encoded")
432 charset, enc := strings.ToLower(fields[1]), strings.ToLower(fields[2])
433 if charset != "iso-8859-1" && charset != "utf-8" {
434 return "", fmt.Errorf("mail: charset not supported: %q", charset)
437 in := bytes.NewBufferString(fields[3])
441 r = base64.NewDecoder(base64.StdEncoding, in)
445 return "", fmt.Errorf("mail: RFC 2047 encoding not supported: %q", enc)
448 dec, err := ioutil.ReadAll(r)
455 b := new(bytes.Buffer)
456 for _, c := range dec {
459 return b.String(), nil
461 return string(dec), nil
466 type qDecoder struct {
471 func (qd qDecoder) Read(p []byte) (n int, err error) {
472 // This method writes at most one byte into p.
476 if _, err := qd.r.Read(qd.scratch[:1]); err != nil {
479 switch c := qd.scratch[0]; {
481 if _, err := io.ReadFull(qd.r, qd.scratch[:2]); err != nil {
484 x, err := strconv.ParseInt(string(qd.scratch[:2]), 16, 64)
486 return 0, fmt.Errorf("mail: invalid RFC 2047 encoding: %q", qd.scratch[:2])
497 var atextChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
498 "abcdefghijklmnopqrstuvwxyz" +
500 "!#$%&'*+-/=?^_`{|}~")
502 // isAtext returns true if c is an RFC 5322 atext character.
503 // If dot is true, period is included.
504 func isAtext(c byte, dot bool) bool {
508 return bytes.IndexByte(atextChars, c) >= 0
511 // isQtext returns true if c is an RFC 5322 qtest character.
512 func isQtext(c byte) bool {
513 // Printable US-ASCII, excluding backslash or quote.
514 if c == '\\' || c == '"' {
517 return '!' <= c && c <= '~'
520 // isVchar returns true if c is an RFC 5322 VCHAR character.
521 func isVchar(c byte) bool {
522 // Visible (printing) characters.
523 return '!' <= c && c <= '~'