-
Notifications
You must be signed in to change notification settings - Fork 1
/
mbox.go
85 lines (68 loc) · 1.98 KB
/
mbox.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"io"
"regexp"
"time"
)
////////////////////////////////////////////////////////////////////////////
// Constant and data type/structure definitions
const envelopeFrom = "cloudmail"
type mbox struct {
io.Writer
}
// Message filter call-back function type: validation
type validation func([]byte, time.Time) error
////////////////////////////////////////////////////////////////////////////
// Function definitions
// emptyFilter implements validation, accepting every mail message
func emptyFilter(rfc822 []byte, envelopeDate time.Time) error {
return nil
}
func newMbox(w io.Writer) *mbox {
return &mbox{w}
}
func (m *mbox) writeMessage(rfc822 []byte, okToGo validation) error {
r := regexp.MustCompile(`\nDate: +(.*?)\r*\n`).FindSubmatch(rfc822)
r1 := regexp.MustCompile(` \([A-Z]{3}[0-9:+-]*\)$`).ReplaceAll(r[1], []byte(""))
//r1 = regexp.MustCompile(` {2,}`).ReplaceAll(r1, []byte(" "))
sendDate := string(r1)
//fmt.Printf("\nsendDate: %+v\n", sendDate)
// Standard RFC1123(Z)
t, err := time.Parse(time.RFC1123, sendDate)
if err != nil {
t, err = time.Parse(time.RFC1123Z, sendDate)
}
// Go time.Parse is too strict
// https://groups.google.com/d/msg/golang-nuts/1iLoXTx3qxU/z4VolJPKGQAJ
// Deal with RFC1123(Z) without leading zero or space
if err != nil {
t, err = time.Parse("Mon, 2 Jan 2006 15:04:05 MST", sendDate)
}
if err != nil {
t, err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", sendDate)
}
if err != nil {
t = time.Now()
}
envelopeDate := t.Format(time.ANSIC)
_ = validation(okToGo) // confirm okToGo satisfies validation at runtime
if err = okToGo(rfc822, t); err != nil {
return err
}
_, err = m.Write([]byte(fmt.Sprintf("From %s %s\r\n", envelopeFrom, envelopeDate)))
if err != nil {
return err
}
// fromEncoded
_, err = m.Write(regexp.MustCompile(`(\n)(From )`).
ReplaceAll(rfc822, []byte("$1>$2")))
if err != nil {
return err
}
_, err = m.Write([]byte("\r\n"))
if err != nil {
return err
}
return nil
}