/
fetch_emails.go
318 lines (269 loc) · 7.2 KB
/
fetch_emails.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright 2023 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package email
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"log/slog"
"slices"
"sort"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
"github.com/emersion/go-message/charset"
)
// Predefine some mailboxes.
const (
Inbox = "INBOX"
)
var (
emailFetchItems1 = []imap.FetchItem{imap.FetchInternalDate, imap.FetchEnvelope, imap.FetchUid, imap.FetchFlags}
emailFetchItems2 = []imap.FetchItem{imap.FetchInternalDate, imap.FetchEnvelope, imap.FetchUid, imap.FetchFlags, imap.FetchBody}
emailStoreItem = imap.FormatFlagsOp(imap.AddFlags, true)
emailReadFlags = []interface{}{imap.SeenFlag}
)
func init() {
// Use charset.Reader to support the encodings, such as GB2312, GB18030, etc.
imap.CharsetReader = charset.Reader
}
// Address represents an email address.
type Address struct {
Name string
Addr string
}
// FullAddress returns the full address with the name if name is not empty.
func (a Address) FullAddress() string {
if a.Name == "" {
return a.Addr
}
return fmt.Sprintf("%s<%s>", a.Name, a.Addr)
}
var _ json.Marshaler = Address{}
// MarshalJSON implements the interface json.Marshaler.
func (a Address) MarshalJSON() ([]byte, error) {
return json.Marshal(a.FullAddress())
}
// Email represents an email message.
type Email struct {
Froms []Address
Senders []Address
Subject string
SentDate time.Time // The date when the message is sent.
RecievedDate time.Time // The date when the mail server recieves the message.
uid uint32
read bool
mailbox string
client *client.Client
}
func newEmail(client *client.Client, mailbox string, msg *imap.Message) (m Email) {
m.Senders = make([]Address, len(msg.Envelope.Sender))
for i, sender := range msg.Envelope.Sender {
m.Senders[i] = Address{
Name: sender.PersonalName,
Addr: sender.Address(),
}
}
m.Froms = make([]Address, len(msg.Envelope.From))
for i, sender := range msg.Envelope.From {
m.Froms[i] = Address{
Name: sender.PersonalName,
Addr: sender.Address(),
}
}
m.Subject = msg.Envelope.Subject
m.SentDate = msg.Envelope.Date
m.RecievedDate = msg.InternalDate
m.read = slices.Contains(msg.Flags, imap.SeenFlag)
m.mailbox = mailbox
m.client = client
m.uid = msg.Uid
return
}
var _ json.Marshaler = Email{}
// MarshalJSON implements the interface json.Marshaler.
func (m Email) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"Froms": m.Froms,
"Senders": m.Senders,
"Subject": m.Subject,
"IsRead": m.IsRead(),
"Mailbox": m.Mailbox(),
"Date": m.Date(),
})
}
// Sender returns the email address of the first sender.
func (m Email) Sender() (sender string) {
if len(m.Senders) > 0 {
sender = m.Senders[0].Addr
} else if len(m.Froms) > 0 {
sender = m.Froms[0].Addr
}
return
}
// Date returns the date when the message is sent.
func (m Email) Date() (date time.Time) {
if !m.SentDate.IsZero() {
return m.SentDate
}
return m.RecievedDate
}
// UID returns the uid of the email.
func (m Email) UID() uint32 { return m.uid }
// IsRead reports whether the message has been read.
func (m Email) IsRead() bool { return m.read }
// Mailbox returns the current mailbox which the message is in.
func (m Email) Mailbox() string { return m.mailbox }
// SetRead marks the message to be read.
func (m *Email) SetRead() (err error) {
if m.IsRead() {
return
}
seqSet := new(imap.SeqSet)
seqSet.AddNum(m.uid)
err = m.client.UidStore(seqSet, emailStoreItem, emailReadFlags, nil)
if err == nil {
m.read = true
}
return
}
// Move moves the message to the given box.
func (m *Email) Move(box string) (err error) {
if m.Mailbox() == box {
return
}
seqSet := new(imap.SeqSet)
seqSet.AddNum(m.uid)
err = m.client.UidMove(seqSet, box)
if err == nil {
m.mailbox = box
}
return
}
// FetchEmails fetches the emails from the mailbox.
//
// If mailbox is eqial to "", use Inbox instead.
// If maxnum is equal 0, use 100 instead.
func FetchEmails(ctx context.Context, addr, username, password, mailbox string,
tlsconfig *tls.Config, maxnum uint32, chains ...Handler) (emails []Email, goon bool, err error) {
return fetchEmails(ctx, addr, username, password, mailbox, tlsconfig, false, maxnum, chains...)
}
func fetchEmails(ctx context.Context, addr, username, password, mailbox string,
tlsconfig *tls.Config, body bool, maxnum uint32, chains ...Handler) (
emails []Email, goon bool, err error) {
if addr == "" {
panic("mail server address must not be empty")
}
if username == "" {
panic("email username must not be empty")
}
if password == "" {
panic("email password must not be empty")
}
var imapClient *client.Client
if tlsconfig != nil {
imapClient, err = client.DialTLS(addr, tlsconfig)
} else {
imapClient, err = client.Dial(addr)
}
if err != nil {
return
}
defer imapClient.Terminate()
err = imapClient.Login(username, password)
if err != nil {
return
}
defer imapClient.Logout()
if mailbox == "" {
mailbox = Inbox
}
mailboxStatus, err := imapClient.Select(mailbox, false)
if err != nil {
return
}
if maxnum <= 0 {
maxnum = 100
}
var startid uint32
stopid := mailboxStatus.Messages
if stopid > maxnum {
startid = stopid - maxnum - 1
}
done := make(chan error)
emails = make([]Email, 0, maxnum)
messages := make(chan *imap.Message, maxnum)
defer func() {
for _, email := range emails {
if !email.IsRead() {
goon = true
break
}
}
_emails := make([]Email, 0, len(emails))
for i := range emails {
if email := emails[i]; handleEmailMessage(&email, chains) {
_emails = append(_emails, email)
}
}
emails = _emails
sort.SliceStable(emails, func(i, j int) bool {
return emails[j].uid < emails[i].uid
})
}()
go func() {
fetchItems := emailFetchItems1
if body {
fetchItems = emailFetchItems2
}
seqset := new(imap.SeqSet)
seqset.AddRange(startid, stopid)
done <- imapClient.Fetch(seqset, fetchItems, messages)
}()
for {
select {
case <-ctx.Done():
err = ctx.Err()
return
case err = <-done:
if err != nil {
return
}
case msg, ok := <-messages:
if !ok {
return
}
emails = append(emails, newEmail(imapClient, mailbox, msg))
}
}
}
func handleEmailMessage(e *Email, chains []Handler) bool {
for _, h := range chains {
next, err := h.Handle(e)
if err != nil {
slog.Error("fail to handle the email",
"handler", h.Type(), "mailbox", e.mailbox, "uid", e.uid,
"sender", e.Sender(), "subject", e.Subject, "err", err.Error())
} else if !next {
if !e.IsRead() {
slog.Debug("ignore the email",
"handler", h.Type(), "mailbox", e.mailbox, "uid", e.uid,
"sender", e.Sender(), "subject", e.Subject)
}
return false
}
}
return true
}