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
|
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/emersion/go-mbox"
"github.com/emersion/go-message/mail"
_ "github.com/emersion/go-message/charset"
)
// Prints the email addresses (one per line) of all senders by parsing an MBOX.
func main() {
mboxNamePtr := flag.String("mbox", "test.mbox", "MBOX to read")
flag.Parse()
PrintAllMboxSenders(*mboxNamePtr)
}
func PrintAllMboxSenders(fileName string) {
f, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
fr := bufio.NewReader(f)
mr := mbox.NewReader(fr)
for {
r, err := mr.NextMessage()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
PrintMessageSender(r)
}
}
func PrintMessageSender(r io.Reader) {
mr, err := mail.CreateReader(r)
if err != nil {
if err.Error() == "charset \"cp-850\": ianaindex: invalid encoding name" {
fmt.Fprintf(os.Stderr, "Ignored a mail due to an invalid charset\n")
return // TODO: Print message ID
}
log.Fatal(err)
}
addr, err := mr.Header.AddressList("From")
if err != nil {
if strings.Contains(err.Error(), "invalid utf-8 in quoted-string") {
addr := strings.TrimPrefix(err.Error(), "mail: missing word in phrase: mail: invalid utf-8 in quoted-string: ")
fmt.Fprintf(os.Stderr, "Ignored due to invalid UTF-8 encoding: %v\n", addr)
return
} else if err.Error() == "mail: missing @ in addr-spec" {
fmt.Fprintf(os.Stderr, "Ignored a sender due to missing @\n")
return // TODO: Print invalid address
} else if err.Error() == "mail: no angle-addr" {
fmt.Fprintf(os.Stderr, "Ignored a mail due to no angle-address\n")
return // TODO: Print message ID
}
log.Fatal(err)
} else if len(addr) != 1 {
if len(addr) == 0 {
fmt.Fprintf(os.Stderr, "Ignored a mail due to a missing sender\n")
return // TODO: Print message ID
}
fmt.Fprintf(os.Stderr, "A mail has an unexpected number of senders: %v\n", len(addr))
return // TODO: Print message ID
}
fmt.Println(addr[0].Address)
}
|