-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.go
1318 lines (1182 loc) · 30 KB
/
main.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package imap
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"io"
"mime"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
retry "github.com/StirlingMarketingGroup/go-retry"
"github.com/davecgh/go-spew/spew"
humanize "github.com/dustin/go-humanize"
"github.com/jhillyerd/enmime"
"github.com/logrusorgru/aurora"
"github.com/rs/xid"
"github.com/sqs/go-xoauth2"
"golang.org/x/net/html/charset"
)
// AddSlashes adds slashes to double quotes
var AddSlashes = strings.NewReplacer(`"`, `\"`)
// RemoveSlashes removes slashes before double quotes
var RemoveSlashes = strings.NewReplacer(`\"`, `"`)
// Verbose outputs every command and its response with the IMAP server
var Verbose = false
// SkipResponses skips printing server responses in verbose mode
var SkipResponses = false
// RetryCount is the number of times retired functions get retried
var RetryCount = 10
var lastResp string
// Dialer is basically an IMAP connection
type Dialer struct {
conn *tls.Conn
Folder string
Username string
Password string
Host string
Port int
strtokI int
strtok string
Connected bool
ConnNum int
}
// EmailAddresses are a map of email address to names
type EmailAddresses map[string]string
// Email is an email message
type Email struct {
Flags []string
Received time.Time
Sent time.Time
Size uint64
Subject string
UID int
MessageID string
From EmailAddresses
To EmailAddresses
ReplyTo EmailAddresses
CC EmailAddresses
BCC EmailAddresses
Text string
HTML string
Attachments []Attachment
}
// Attachment is an Email attachment
type Attachment struct {
Name string
MimeType string
Content []byte
}
func (e EmailAddresses) String() string {
emails := strings.Builder{}
i := 0
for e, n := range e {
if i != 0 {
emails.WriteString(", ")
}
if len(n) != 0 {
if strings.ContainsRune(n, ',') {
emails.WriteString(fmt.Sprintf(`"%s" <%s>`, AddSlashes.Replace(n), e))
} else {
emails.WriteString(fmt.Sprintf(`%s <%s>`, n, e))
}
} else {
emails.WriteString(e)
}
i++
}
return emails.String()
}
func (e Email) String() string {
email := strings.Builder{}
email.WriteString(fmt.Sprintf("Subject: %s\n", e.Subject))
if len(e.To) != 0 {
email.WriteString(fmt.Sprintf("To: %s\n", e.To))
}
if len(e.From) != 0 {
email.WriteString(fmt.Sprintf("From: %s\n", e.From))
}
if len(e.CC) != 0 {
email.WriteString(fmt.Sprintf("CC: %s\n", e.CC))
}
if len(e.BCC) != 0 {
email.WriteString(fmt.Sprintf("BCC: %s\n", e.BCC))
}
if len(e.ReplyTo) != 0 {
email.WriteString(fmt.Sprintf("ReplyTo: %s\n", e.ReplyTo))
}
if len(e.Text) != 0 {
if len(e.Text) > 20 {
email.WriteString(fmt.Sprintf("Text: %s...", e.Text[:20]))
} else {
email.WriteString(fmt.Sprintf("Text: %s", e.Text))
}
email.WriteString(fmt.Sprintf("(%s)\n", humanize.Bytes(uint64(len(e.Text)))))
}
if len(e.HTML) != 0 {
if len(e.HTML) > 20 {
email.WriteString(fmt.Sprintf("HTML: %s...", e.HTML[:20]))
} else {
email.WriteString(fmt.Sprintf("HTML: %s", e.HTML))
}
email.WriteString(fmt.Sprintf(" (%s)\n", humanize.Bytes(uint64(len(e.HTML)))))
}
if len(e.Attachments) != 0 {
email.WriteString(fmt.Sprintf("%d Attachment(s): %s\n", len(e.Attachments), e.Attachments))
}
return email.String()
}
func (a Attachment) String() string {
return fmt.Sprintf("%s (%s %s)", a.Name, a.MimeType, humanize.Bytes(uint64(len(a.Content))))
}
var nextConnNum = 0
var nextConnNumMutex = sync.RWMutex{}
func log(connNum int, folder string, msg interface{}) {
var name string
if len(folder) != 0 {
name = fmt.Sprintf("IMAP%d:%s", connNum, folder)
} else {
name = fmt.Sprintf("IMAP%d", connNum)
}
fmt.Println(aurora.Sprintf("%s %s: %s", time.Now().Format("2006-01-02 15:04:05.000000"), aurora.Colorize(name, aurora.CyanFg|aurora.BoldFm), msg))
}
// NewWithOAuth2 makes a new imap with OAuth2
func NewWithOAuth2(username string, accessToken string, host string, port int) (d *Dialer, err error) {
nextConnNumMutex.RLock()
connNum := nextConnNum
nextConnNumMutex.RUnlock()
nextConnNumMutex.Lock()
nextConnNum++
nextConnNumMutex.Unlock()
err = retry.Retry(func() error {
if Verbose {
log(connNum, "", aurora.Green(aurora.Bold("establishing connection")))
}
var conn *tls.Conn
conn, err = tls.Dial("tcp", host+":"+strconv.Itoa(port), nil)
if err != nil {
if Verbose {
log(connNum, "", aurora.Red(aurora.Bold(fmt.Sprintf("failed to connect: %s", err))))
}
return err
}
d = &Dialer{
conn: conn,
Username: username,
Password: accessToken,
Host: host,
Port: port,
Connected: true,
ConnNum: connNum,
}
return d.Authenticate(username, accessToken)
}, RetryCount, func(err error) error {
if Verbose {
log(connNum, "", aurora.Yellow(aurora.Bold("failed to establish connection, retrying shortly")))
if d != nil && d.conn != nil {
d.conn.Close()
}
}
return nil
}, func() error {
if Verbose {
log(connNum, "", aurora.Yellow(aurora.Bold("retrying failed connection now")))
}
return nil
})
if err != nil {
if Verbose {
log(connNum, "", aurora.Red(aurora.Bold("failed to establish connection")))
if d != nil && d.conn != nil {
d.conn.Close()
}
}
return nil, err
}
return
}
// New makes a new imap
func New(username string, password string, host string, port int) (d *Dialer, err error) {
nextConnNumMutex.RLock()
connNum := nextConnNum
nextConnNumMutex.RUnlock()
nextConnNumMutex.Lock()
nextConnNum++
nextConnNumMutex.Unlock()
err = retry.Retry(func() error {
if Verbose {
log(connNum, "", aurora.Green(aurora.Bold("establishing connection")))
}
var conn *tls.Conn
conn, err = tls.Dial("tcp", host+":"+strconv.Itoa(port), nil)
if err != nil {
if Verbose {
log(connNum, "", aurora.Red(aurora.Bold(fmt.Sprintf("failed to connect: %s", err))))
}
return err
}
d = &Dialer{
conn: conn,
Username: username,
Password: password,
Host: host,
Port: port,
Connected: true,
ConnNum: connNum,
}
return d.Login(username, password)
}, RetryCount, func(err error) error {
if Verbose {
log(connNum, "", aurora.Yellow(aurora.Bold("failed to establish connection, retrying shortly")))
if d != nil && d.conn != nil {
d.conn.Close()
}
}
return nil
}, func() error {
if Verbose {
log(connNum, "", aurora.Yellow(aurora.Bold("retrying failed connection now")))
}
return nil
})
if err != nil {
if Verbose {
log(connNum, "", aurora.Red(aurora.Bold("failed to establish connection")))
if d != nil && d.conn != nil {
d.conn.Close()
}
}
return nil, err
}
return
}
// Clone returns a new connection with the same connection information
// as the one this is being called on
func (d *Dialer) Clone() (d2 *Dialer, err error) {
d2, err = New(d.Username, d.Password, d.Host, d.Port)
// d2.Verbose = d1.Verbose
if d.Folder != "" {
err = d2.SelectFolder(d.Folder)
if err != nil {
return nil, fmt.Errorf("imap clone: %s", err)
}
}
return
}
// Close closes the imap connection
func (d *Dialer) Close() (err error) {
if d.Connected {
if Verbose {
log(d.ConnNum, d.Folder, aurora.Yellow(aurora.Bold("closing connection")))
}
err = d.conn.Close()
if err != nil {
return fmt.Errorf("imap close: %s", err)
}
d.Connected = false
}
return
}
// Reconnect closes the current connection (if any) and establishes a new one
func (d *Dialer) Reconnect() (err error) {
d.Close()
if Verbose {
log(d.ConnNum, d.Folder, aurora.Yellow(aurora.Bold("reopening connection")))
}
d2, err := d.Clone()
if err != nil {
return fmt.Errorf("imap reconnect: %s", err)
}
*d = *d2
return
}
const nl = "\r\n"
func dropNl(b []byte) []byte {
if len(b) >= 1 && b[len(b)-1] == '\n' {
if len(b) >= 2 && b[len(b)-2] == '\r' {
return b[:len(b)-2]
} else {
return b[:len(b)-1]
}
}
return b
}
var atom = regexp.MustCompile(`{\d+}$`)
// Exec executes the command on the imap connection
func (d *Dialer) Exec(command string, buildResponse bool, retryCount int, processLine func(line []byte) error) (response string, err error) {
var resp strings.Builder
err = retry.Retry(func() (err error) {
tag := []byte(fmt.Sprintf("%X", xid.New()))
c := fmt.Sprintf("%s %s\r\n", tag, command)
if Verbose {
log(d.ConnNum, d.Folder, strings.Replace(fmt.Sprintf("%s %s", aurora.Bold("->"), strings.TrimSpace(c)), fmt.Sprintf(`"%s"`, d.Password), `"****"`, -1))
}
_, err = d.conn.Write([]byte(c))
if err != nil {
return
}
r := bufio.NewReader(d.conn)
if buildResponse {
resp = strings.Builder{}
}
var line []byte
for err == nil {
line, err = r.ReadBytes('\n')
for {
if a := atom.Find(dropNl(line)); a != nil {
// fmt.Printf("%s\n", a)
var n int
n, err = strconv.Atoi(string(a[1 : len(a)-1]))
if err != nil {
return
}
buf := make([]byte, n)
_, err = io.ReadFull(r, buf)
if err != nil {
return
}
line = append(line, buf...)
buf, err = r.ReadBytes('\n')
if err != nil {
return
}
line = append(line, buf...)
continue
}
break
}
if Verbose && !SkipResponses {
log(d.ConnNum, d.Folder, fmt.Sprintf("<- %s", dropNl(line)))
}
// if strings.Contains(string(line), "--00000000000030095105741e7f1f") {
// f, _ := ioutil.TempFile("", "")
// ioutil.WriteFile(f.Name(), line, 0777)
// fmt.Println(f.Name())
// }
// XID project is returning 40-byte tags. The code was originally hardcoded 16 digits.
taglen := len(tag)
oklen := 3
if len(line) >= taglen+oklen && bytes.Equal(line[:taglen], tag) {
if !bytes.Equal(line[taglen+1:taglen+oklen], []byte("OK")) {
err = fmt.Errorf("imap command failed: %s", line[taglen+oklen+1:])
return
}
break
}
if processLine != nil {
if err = processLine(line); err != nil {
return
}
}
if buildResponse {
resp.Write(line)
}
}
return
}, retryCount, func(err error) error {
if Verbose {
log(d.ConnNum, d.Folder, aurora.Red(err))
}
d.Close()
return nil
}, func() error {
return d.Reconnect()
})
if err != nil {
if Verbose {
log(d.ConnNum, d.Folder, aurora.Red(aurora.Bold("All retries failed")))
}
return "", err
}
if buildResponse {
if resp.Len() != 0 {
lastResp = resp.String()
return lastResp, nil
}
return "", nil
}
return
}
func (d *Dialer) Authenticate(user string, accessToken string) (err error) {
b64 := xoauth2.XOAuth2String(user, accessToken)
_, err = d.Exec(fmt.Sprintf("AUTHENTICATE XOAUTH2 %s", b64), false, RetryCount, nil)
return
}
// Login attempts to login
func (d *Dialer) Login(username string, password string) (err error) {
_, err = d.Exec(fmt.Sprintf(`LOGIN "%s" "%s"`, AddSlashes.Replace(username), AddSlashes.Replace(password)), false, RetryCount, nil)
return
}
// GetFolders returns all folders
func (d *Dialer) GetFolders() (folders []string, err error) {
folders = make([]string, 0)
_, err = d.Exec(`LIST "" "*"`, false, RetryCount, func(line []byte) (err error) {
line = dropNl(line)
if b := bytes.IndexByte(line, '\n'); b != -1 {
folders = append(folders, string(line[b+1:]))
} else {
if len(line) == 0 {
return
}
i := len(line) - 1
quoted := line[i] == '"'
delim := byte(' ')
if quoted {
delim = '"'
i--
}
end := i
for i > 0 {
if line[i] == delim {
if !quoted || line[i-1] != '\\' {
break
}
}
i--
}
folders = append(folders, RemoveSlashes.Replace(string(line[i+1:end+1])))
}
return
})
if err != nil {
return nil, err
}
return folders, nil
}
func (d *Dialer) runIdleEvent(data []byte, handler *IdleHandler) error {
index := 0
event := ""
if _, err := fmt.Sscanf(string(data), "%d %s", &index, &event); err != nil {
return fmt.Errorf("invalid IDLE event format: %s", data)
}
switch event {
case IdleEventExists:
if handler.OnExists != nil {
handler.OnExists(ExistsEvent{MessageIndex: index})
}
case IdleEventExpunge:
if handler.OnExpunge != nil {
handler.OnExpunge(ExpungeEvent{MessageIndex: index})
}
case IdleEventFetch:
if handler.OnFetch == nil {
return nil
}
str := `9 FETCH (UID 64 FLAGS (\Seen \Answered \Flagged))`
re := regexp.MustCompile(`(\d+) FETCH \(UID (\d+) FLAGS \((.*)\)\)`)
matches := re.FindStringSubmatch(str)
if len(matches) == 4 {
messageIndex, _ := strconv.Atoi(matches[1])
uid, _ := strconv.Atoi(matches[2])
flags := strings.FieldsFunc(strings.ReplaceAll(matches[3], `\`, ""), func(r rune) bool {
return unicode.IsSpace(r) || r == ','
})
handler.OnFetch(FetchEvent{MessageIndex: messageIndex, UID: uint32(uid), Flags: flags})
} else {
return fmt.Errorf("invalid FETCH event format: %s", data)
}
}
return nil
}
func (d *Dialer) StartIdle(handler *IdleHandler) error {
done := make(chan error, 1)
go func() {
defer close(done)
if _, err := d.Exec("IDLE", true, 0, func(line []byte) (err error) {
if bytes.HasPrefix(line, []byte("* ")) {
err := d.runIdleEvent(line[2:], handler)
if err != nil {
fmt.Println(err)
return err
}
} else if bytes.Equal(line, []byte("OK IDLE terminated")) {
done <- nil
}
return
}); err != nil {
done <- err
return
}
}()
return nil
}
var regexExists = regexp.MustCompile(`\*\s+(\d+)\s+EXISTS`)
// GetTotalEmailCount returns the total number of emails in every folder
func (d *Dialer) GetTotalEmailCount() (count int, err error) {
return d.GetTotalEmailCountStartingFromExcluding("", nil)
}
// GetTotalEmailCountExcluding returns the total number of emails in every folder
// excluding the specified folders
func (d *Dialer) GetTotalEmailCountExcluding(excludedFolders []string) (count int, err error) {
return d.GetTotalEmailCountStartingFromExcluding("", excludedFolders)
}
// GetTotalEmailCountStartingFrom returns the total number of emails in every folder
// after the specified start folder
func (d *Dialer) GetTotalEmailCountStartingFrom(startFolder string) (count int, err error) {
return d.GetTotalEmailCountStartingFromExcluding(startFolder, nil)
}
// GetTotalEmailCountStartingFromExcluding returns the total number of emails in every folder
// after the specified start folder, excluding the specified folders
func (d *Dialer) GetTotalEmailCountStartingFromExcluding(startFolder string, excludedFolders []string) (count int, err error) {
started := true
if len(startFolder) != 0 {
started = false
}
folder := d.Folder
folders, err := d.GetFolders()
if err != nil {
return
}
for _, f := range folders {
if !started {
if f == startFolder {
started = true
} else {
continue
}
}
skip := false
for _, ef := range excludedFolders {
if f == ef {
skip = true
break
}
}
if skip {
continue
}
err = d.SelectFolder(f)
if err != nil {
return
}
var n int
n, err = strconv.Atoi(regexExists.FindStringSubmatch(lastResp)[1])
if err != nil {
return
}
count += n
}
if len(folder) != 0 {
err = d.SelectFolder(folder)
if err != nil {
return
}
}
return
}
// SelectFolder selects a folder
func (d *Dialer) SelectFolder(folder string) (err error) {
_, err = d.Exec(`EXAMINE "`+AddSlashes.Replace(folder)+`"`, true, RetryCount, nil)
if err != nil {
return
}
d.Folder = folder
return nil
}
// Move a read email to a specified folder
func (d *Dialer) MoveEmail(uid int, folder string) (err error) {
_, err = d.Exec(`UID MOVE `+strconv.Itoa(uid)+` "`+AddSlashes.Replace(folder)+`"`, true, RetryCount, nil)
if err != nil {
return
}
d.Folder = folder
return nil
}
// GetUIDs returns the UIDs in the current folder that match the search
func (d *Dialer) GetUIDs(search string) (uids []int, err error) {
uids = make([]int, 0)
t := []byte{' ', '\r', '\n'}
r, err := d.Exec(`UID SEARCH `+search, true, RetryCount, nil)
if err != nil {
return nil, err
}
if d.StrtokInit(r, t) == "*" && d.Strtok(t) == "SEARCH" {
for {
uid := string(d.Strtok(t))
if len(uid) == 0 {
break
}
u, err := strconv.Atoi(string(uid))
if err != nil {
return nil, err
}
uids = append(uids, u)
}
}
return uids, nil
}
const (
EDate uint8 = iota
ESubject
EFrom
ESender
EReplyTo
ETo
ECC
EBCC
EInReplyTo
EMessageID
)
const (
EEName uint8 = iota
// EESR is unused and should be ignored
EESR
EEMailbox
EEHost
)
// GetEmails returns email with their bodies for the given UIDs in the current folder.
// If no UIDs are given, then everything in the current folder is selected
func (d *Dialer) GetEmails(uids ...int) (emails map[int]*Email, err error) {
emails, err = d.GetOverviews(uids...)
if err != nil {
return nil, err
}
if len(emails) == 0 {
return
}
uidsStr := strings.Builder{}
if len(uids) == 0 {
uidsStr.WriteString("1:*")
} else {
i := 0
for u := range emails {
if u == 0 {
continue
}
if i != 0 {
uidsStr.WriteByte(',')
}
uidsStr.WriteString(strconv.Itoa(u))
i++
}
}
var records [][]*Token
err = retry.Retry(func() (err error) {
r, err := d.Exec("UID FETCH "+uidsStr.String()+" BODY.PEEK[]", true, 0, nil)
if err != nil {
return
}
records, err = d.ParseFetchResponse(r)
if err != nil {
return
}
for _, tks := range records {
e := &Email{}
skip := 0
success := true
for i, t := range tks {
if skip > 0 {
skip--
continue
}
if err = d.CheckType(t, []TType{TLiteral}, tks, "in root"); err != nil {
return
}
switch t.Str {
case "BODY[]":
if err = d.CheckType(tks[i+1], []TType{TAtom}, tks, "after BODY[]"); err != nil {
return
}
msg := tks[i+1].Str
r := strings.NewReader(msg)
env, err := enmime.ReadEnvelope(r)
if err != nil {
if Verbose {
log(d.ConnNum, d.Folder, aurora.Yellow(aurora.Sprintf("email body could not be parsed, skipping: %s", err)))
spew.Dump(env)
spew.Dump(msg)
// os.Exit(0)
}
success = false
// continue RecL
} else {
e.Subject = env.GetHeader("Subject")
e.Text = env.Text
e.HTML = env.HTML
if len(env.Attachments) != 0 {
for _, a := range env.Attachments {
e.Attachments = append(e.Attachments, Attachment{
Name: a.FileName,
MimeType: a.ContentType,
Content: a.Content,
})
}
}
if len(env.Inlines) != 0 {
for _, a := range env.Inlines {
e.Attachments = append(e.Attachments, Attachment{
Name: a.FileName,
MimeType: a.ContentType,
Content: a.Content,
})
}
}
for _, a := range []struct {
dest *EmailAddresses
header string
}{
{&e.From, "From"},
{&e.ReplyTo, "Reply-To"},
{&e.To, "To"},
{&e.CC, "cc"},
{&e.BCC, "bcc"},
} {
alist, _ := env.AddressList(a.header)
(*a.dest) = make(map[string]string, len(alist))
for _, addr := range alist {
(*a.dest)[strings.ToLower(addr.Address)] = addr.Name
}
}
}
skip++
case "UID":
if err = d.CheckType(tks[i+1], []TType{TNumber}, tks, "after UID"); err != nil {
return
}
e.UID = tks[i+1].Num
skip++
}
}
if success {
if emails[e.UID] == nil {
emails[e.UID] = &Email{UID: e.UID}
}
emails[e.UID].Subject = e.Subject
emails[e.UID].From = e.From
emails[e.UID].ReplyTo = e.ReplyTo
emails[e.UID].To = e.To
emails[e.UID].CC = e.CC
emails[e.UID].BCC = e.BCC
emails[e.UID].Text = e.Text
emails[e.UID].HTML = e.HTML
emails[e.UID].Attachments = e.Attachments
} else {
delete(emails, e.UID)
}
}
return
}, RetryCount, func(err error) error {
log(d.ConnNum, d.Folder, aurora.Red(aurora.Bold(err)))
d.Close()
return nil
}, func() error {
return d.Reconnect()
})
return
}
// GetOverviews returns emails without bodies for the given UIDs in the current folder.
// If no UIDs are given, then everything in the current folder is selected
func (d *Dialer) GetOverviews(uids ...int) (emails map[int]*Email, err error) {
uidsStr := strings.Builder{}
if len(uids) == 0 {
uidsStr.WriteString("1:*")
} else {
for i, u := range uids {
if u == 0 {
continue
}
if i != 0 {
uidsStr.WriteByte(',')
}
uidsStr.WriteString(strconv.Itoa(u))
}
}
var records [][]*Token
err = retry.Retry(func() (err error) {
r, err := d.Exec("UID FETCH "+uidsStr.String()+" ALL", true, 0, nil)
if err != nil {
return
}
if len(r) == 0 {
return
}
records, err = d.ParseFetchResponse(r)
if err != nil {
return
}
return
}, RetryCount, func(err error) error {
log(d.ConnNum, d.Folder, aurora.Red(aurora.Bold(err)))
d.Close()
return nil
}, func() error {
return d.Reconnect()
})
if err != nil {
return nil, err
}
emails = make(map[int]*Email, len(uids))
CharsetReader := func(label string, input io.Reader) (io.Reader, error) {
label = strings.Replace(label, "windows-", "cp", -1)
encoding, _ := charset.Lookup(label)
return encoding.NewDecoder().Reader(input), nil
}
dec := mime.WordDecoder{CharsetReader: CharsetReader}
// RecordsL:
for _, tks := range records {
e := &Email{}
skip := 0
for i, t := range tks {
if skip > 0 {
skip--
continue
}
if err = d.CheckType(t, []TType{TLiteral}, tks, "in root"); err != nil {
return nil, err
}
switch t.Str {
case "FLAGS":
if err = d.CheckType(tks[i+1], []TType{TContainer}, tks, "after FLAGS"); err != nil {
return nil, err
}
e.Flags = make([]string, len(tks[i+1].Tokens))
for i, t := range tks[i+1].Tokens {
if err = d.CheckType(t, []TType{TLiteral}, tks, "for FLAGS[%d]", i); err != nil {
return nil, err
}
e.Flags[i] = t.Str
}
skip++
case "INTERNALDATE":
if err = d.CheckType(tks[i+1], []TType{TQuoted}, tks, "after INTERNALDATE"); err != nil {
return nil, err
}
e.Received, err = time.Parse(TimeFormat, tks[i+1].Str)
if err != nil {
return nil, err
}
e.Received = e.Received.UTC()
skip++
case "RFC822.SIZE":
if err = d.CheckType(tks[i+1], []TType{TNumber}, tks, "after RFC822.SIZE"); err != nil {
return nil, err
}
e.Size = uint64(tks[i+1].Num)
skip++
case "ENVELOPE":
if err = d.CheckType(tks[i+1], []TType{TContainer}, tks, "after ENVELOPE"); err != nil {
return nil, err
}
if err = d.CheckType(tks[i+1].Tokens[EDate], []TType{TQuoted, TNil}, tks, "for ENVELOPE[%d]", EDate); err != nil {
return nil, err
}
if err = d.CheckType(tks[i+1].Tokens[ESubject], []TType{TQuoted, TAtom, TNil}, tks, "for ENVELOPE[%d]", ESubject); err != nil {
return nil, err
}
e.Sent, _ = time.Parse("Mon, _2 Jan 2006 15:04:05 -0700", tks[i+1].Tokens[EDate].Str)
e.Sent = e.Sent.UTC()
e.Subject, err = dec.DecodeHeader(tks[i+1].Tokens[ESubject].Str)
if err != nil {
return nil, err
}
for _, a := range []struct {
dest *EmailAddresses
pos uint8
debug string
}{
{&e.From, EFrom, "FROM"},
{&e.ReplyTo, EReplyTo, "REPLYTO"},
{&e.To, ETo, "TO"},
{&e.CC, ECC, "CC"},
{&e.BCC, EBCC, "BCC"},
} {
if tks[i+1].Tokens[EFrom].Type != TNil {
if err = d.CheckType(tks[i+1].Tokens[a.pos], []TType{TNil, TContainer}, tks, "for ENVELOPE[%d]", a.pos); err != nil {
return nil, err
}
*a.dest = make(map[string]string, len(tks[i+1].Tokens[EFrom].Tokens))
for i, t := range tks[i+1].Tokens[a.pos].Tokens {
if err = d.CheckType(t.Tokens[EEName], []TType{TQuoted, TNil}, tks, "for %s[%d][%d]", a.debug, i, EEName); err != nil {
return nil, err
}