main.go (view raw)
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "encoding/json"
7 "io"
8 "io/ioutil"
9 "log"
10 "net/http"
11 "os"
12 "strings"
13
14 "github.com/emersion/go-message/mail"
15)
16
17type P map[string]string
18
19type Mail struct {
20 From string
21 Date string
22 ReplyTo string
23 Parts []P
24}
25
26func makeReq(j []byte) {
27 req, err := http.NewRequest("POST", "http://localhost:8001/webhook", bytes.NewBuffer(j))
28 req.Header.Set("Content-Type", "application/json")
29 client := http.Client{}
30 res, err := client.Do(req)
31 if err != nil {
32 log.Fatal(err)
33 }
34 defer res.Body.Close()
35}
36
37func main() {
38 r := bufio.NewReader(os.Stdin)
39 mr, err := mail.CreateReader(r)
40
41 newmail := Mail{}
42 newmail.Date = mr.Header.Get("Date")
43 newmail.From = mr.Header.Get("From")
44 newmail.ReplyTo = mr.Header.Get("Reply-To")
45
46 if err != nil {
47 log.Fatal(err)
48 }
49
50 for {
51 p, err := mr.NextPart()
52 if err == io.EOF {
53 break
54 } else if err != nil {
55 log.Fatal(err)
56 }
57 switch h := p.Header.(type) {
58 case *mail.InlineHeader:
59 ct := strings.Split(p.Header.Get("Content-Type"), ";")[0]
60 b, _ := ioutil.ReadAll(p.Body)
61 part := P{ct: string(b)}
62 newmail.Parts = append(newmail.Parts, part)
63
64 case *mail.AttachmentHeader:
65 filename, _ := h.Filename()
66 log.Printf("Got attachment: %v\n", filename)
67 }
68 }
69
70 j, err := json.Marshal(newmail)
71 if err != nil {
72 log.Fatal(err)
73 }
74 makeReq(j)
75 log.Printf("sent webhook: %v\n", newmail.From)
76}