-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetchemail.go
254 lines (213 loc) · 6.31 KB
/
fetchemail.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
package main
import (
"errors"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/mail"
"net/url"
"regexp"
"strings"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
)
const responseSubscribeSubject = "[rss-email] successfully subscribe"
const responseSubscribeSubjectFail = "[rss-email] unsuccessfully subscribe"
const responseListSubject = "[rss-email] list command response"
const responseUnsubscribeSubject = "[rss-email] successfully unsubscribe"
const responseNotSubscribeSubject = "[rss-email] you haven't subscribed yet."
const responseNotSubscribeBody = "you haven't subscribed yet."
const responseSubjectHelp = "[rss-email] unrecognized command"
const responseBodyHelp = `
<h3>Usage:</h3>
<p>Email subject: rss-email [COMMAND]</p>
<p>COMMAND is one of : subscribe, list, unsubscribe</p>
<br>
<p>For more details: https://github.com/derekchuank/rss-email</p>
`
const httpRegex = `(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+\r\n`
func fetchemail(config *emailConfig) error {
c, err := client.DialTLS(config.imapServer, nil)
if err != nil {
return err
}
defer c.Logout()
if err := c.Login(config.username, config.password); err != nil {
return err
}
if err := fetchFromBox(config, c, "INBOX"); err != nil {
log.Printf("error fetchFromBox INBOX")
}
// Junk can contain messages useful
if err := fetchFromBox(config, c, "Junk"); err != nil {
log.Printf("error fetchFromBox Junk")
}
return nil
}
func fetchFromBox(config *emailConfig, c *client.Client, boxType string) error {
mbox, err := c.Select(boxType, false)
if err != nil {
return err
}
if mbox.UnseenSeqNum == 0 {
log.Println("no unseen emails")
return nil
}
from := mbox.UnseenSeqNum
to := mbox.Messages
seqset := new(imap.SeqSet)
seqset.AddRange(from, to)
messages := make(chan *imap.Message, 10)
done := make(chan error, 1)
// Get the whole message body
section := &imap.BodySectionName{}
items := []imap.FetchItem{section.FetchItem()}
go func() {
done <- c.Fetch(seqset, items, messages)
}()
for msg := range messages {
r := msg.GetBody(section)
if r == nil {
return errors.New("Server didn't returned message body")
}
msg, err := mail.ReadMessage(r)
if err != nil {
return err
}
header := msg.Header
fromAddress, err := mail.ParseAddress(header.Get("From"))
if err != nil {
log.Println("errors parsing fromAddress")
}
fromAddressAddress := fromAddress.Address
subject := header.Get("Subject")
subjectArgs := strings.SplitN(subject, " ", 2)
if subjectArgs[0] != "rss-email" {
log.Println("get one non-rss-email email")
continue
}
log.Println("get one rss-email email")
var command string
if len(subjectArgs) == 2 {
command = subjectArgs[1]
}
// process emails recieved
if command == "subscribe" {
slurp, err := parseMultipart(msg)
if err != nil {
if err := sendemail(config, fromAddressAddress, responseSubscribeSubjectFail, err.Error()); err != nil {
log.Printf("error sendemail in subscribe response")
continue
}
continue
}
re := regexp.MustCompile(httpRegex)
urlStrs := re.FindAll(slurp, -1)
var validUrls []string
for _, urlStr := range urlStrs {
urlStr = urlStr[:len(urlStr)-2]
u, err := url.Parse(string(urlStr))
if err != nil {
log.Println(err)
continue
}
validUrls = append(validUrls, u.String())
}
if len(validUrls) == 0 {
failBody := "This is the mail body we received: " + string(slurp)
if err := sendemail(config, fromAddressAddress, responseSubscribeSubjectFail, failBody); err != nil {
log.Printf("error sendemail in subscribe response")
continue
}
continue
}
userSubscriptions.m[fromAddressAddress] = newUserSubscription()
for _, url := range validUrls {
(*userSubscriptions.m[fromAddressAddress])[url] = newUserURLInfo()
}
responseBody, err := userSubscriptions.m[fromAddressAddress].printToUser()
if err != nil {
log.Println("error printToUser")
continue
}
if err := sendemail(config, fromAddressAddress, responseSubscribeSubject, responseBody); err != nil {
log.Printf("error sendemail in subscribe response")
continue
}
continue
}
if command == "list" {
_, ok := userSubscriptions.m[fromAddressAddress]
if !ok {
if err := sendemail(config, fromAddressAddress, responseNotSubscribeSubject, responseNotSubscribeBody); err != nil {
log.Printf("error sendemail in failed list response")
continue
}
continue
}
responseBody, err := userSubscriptions.m[fromAddressAddress].printToUser()
if err != nil {
log.Println("error printToUser")
continue
}
if err := sendemail(config, fromAddressAddress, responseListSubject, responseBody); err != nil {
log.Printf("error sendemail in list response")
continue
}
continue
}
if command == "unsubscribe" {
_, ok := userSubscriptions.m[fromAddressAddress]
if !ok {
if err := sendemail(config, fromAddressAddress, responseNotSubscribeSubject, responseNotSubscribeBody); err != nil {
log.Printf("error sendemail in failed unsubscribe response")
continue
}
}
delete(userSubscriptions.m, fromAddressAddress)
if err := sendemail(config, fromAddressAddress, responseUnsubscribeSubject, ""); err != nil {
log.Printf("error sendemail in unsubscribe response")
continue
}
continue
}
if err := sendemail(config, fromAddressAddress, responseSubjectHelp, responseBodyHelp); err != nil {
log.Printf("error sendemail in response help")
continue
}
}
if err := <-done; err != nil {
return err
}
return nil
}
func parseMultipart(msg *mail.Message) ([]byte, error) {
mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
if strings.HasPrefix(mediaType, "multipart/") {
mr := multipart.NewReader(msg.Body, params["boundary"])
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
slurp, err := ioutil.ReadAll(p)
if err != nil {
return nil, err
}
contentType := p.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/plain") {
return slurp, nil
}
}
return nil, errors.New("received email not valid mime multipart")
}
return nil, errors.New("received email not multipart content type")
}