-
Notifications
You must be signed in to change notification settings - Fork 1
/
imap.go
122 lines (95 loc) · 2.29 KB
/
imap.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
i "github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
"github.com/emersion/go-message/charset"
m "github.com/emersion/go-message/mail"
"github.com/pkg/errors"
"golang.org/x/text/encoding/charmap"
"log"
"strings"
"time"
"unicode/utf8"
)
type imap struct {
Username string
Password string
Server string
Port string
Client *client.Client
}
func (imap *imap) connect() error {
c, err := client.DialTLS(imap.Server+":"+imap.Port, nil)
if err != nil {
return err
}
imap.Client = c
return nil
}
func (imap *imap) login() error {
return imap.Client.Login(imap.Username, imap.Password)
}
func (imap *imap) selectMailbox(mailbox string) (*i.MailboxStatus, error) {
return imap.Client.Select(mailbox, true)
}
func (imap *imap) search(from, to time.Time) ([]uint32, error) {
search := i.NewSearchCriteria()
search.Since = from
search.Before = to
return imap.Client.UidSearch(search)
}
func (imap *imap) createSeqSet(uids []uint32) *i.SeqSet {
seqset := new(i.SeqSet)
seqset.AddNum(uids...)
return seqset
}
func (imap *imap) enableCharsetReader() {
charset.RegisterEncoding("ansi", charmap.Windows1252)
charset.RegisterEncoding("iso8859-15", charmap.ISO8859_15)
i.CharsetReader = charset.Reader
}
func (imap *imap) fixUtf(str string) string {
callable := func(r rune) rune {
if r == utf8.RuneError {
return -1
}
return r
}
return strings.Map(callable, str)
}
func (imap *imap) fetchMessages(seqset *i.SeqSet, mailsChan chan *mail) error {
messages := make(chan *i.Message)
section := new(i.BodySectionName)
go func() {
if err := imap.Client.UidFetch(seqset, []i.FetchItem{section.FetchItem(), i.FetchEnvelope}, messages); err != nil {
log.Println(err)
}
}()
for message := range messages {
mail := new(mail)
mail.fetchMeta(message)
reader := message.GetBody(section)
if reader == nil {
return errors.New("no reader")
}
mailReader, err := m.CreateReader(reader)
if err != nil {
mail.Error = err
mailsChan <- mail
if mailReader != nil {
if err := mailReader.Close(); err != nil {
log.Fatal(err)
}
}
continue
}
mail.Error = mail.fetchBody(mailReader)
mailsChan <- mail
if mailReader != nil {
if err := mailReader.Close(); err != nil {
log.Fatal(err)
}
}
}
return nil
}