forked from clementlecorre/mail-to-telegram
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reading.go
71 lines (63 loc) · 1.46 KB
/
reading.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
package main
import (
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
"github.com/emersion/go-message/mail"
"io"
"io/ioutil"
"log"
)
type ReadClient struct {
Client *client.Client
Ch chan imap.MailboxStatus
}
func (rc *ReadClient) Loop() {
for upd := range rc.Ch {
rc.Read(upd)
}
}
func (rc *ReadClient) Read(mbox imap.MailboxStatus) {
messages := make(chan *imap.Message, 10)
go rc.ReadMessages(messages)
seq := new(imap.SeqSet)
seq.AddNum(mbox.Messages)
err := rc.Client.Fetch(seq, []imap.FetchItem{imap.FetchRFC822, imap.FetchEnvelope}, messages)
if err != nil {
// Deal with error
log.Println("Fetch error: ", err)
}
}
func (rc *ReadClient) ReadMessages(messages chan *imap.Message) {
for email := range messages {
log.Println("New mail: ")
for _, body := range email.Body {
go MailProcessing(rc.EmailBodyParse(body), email)
}
}
}
func (rc *ReadClient) EmailBodyParse(r io.Reader) []byte {
mr, err := mail.CreateReader(r)
if err != nil {
log.Fatal(err)
}
for {
p, err := mr.NextPart()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
switch h := p.Header.(type) {
case *mail.InlineHeader:
// This is the message's text (can be plain-text or HTML)
b, _ := ioutil.ReadAll(p.Body)
return b
case *mail.AttachmentHeader:
// This is an attachment
filename, _ := h.Filename()
// Unused in my case
log.Println("got attachment: ", filename)
}
}
return []byte{}
}