all repos — mdawh @ 0ff2bd53b5bc2ea01735370c0f61c9598e7c3e11

An MDA that creates a webhook on recieval of mail

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	f, err := os.OpenFile("mdawh.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
39	if err != nil {
40		log.Fatal(err)
41	}
42	defer f.Close()
43	log.SetOutput(f)
44
45	r := bufio.NewReader(os.Stdin)
46	mr, err := mail.CreateReader(r)
47
48	newmail := Mail{}
49	newmail.Date = mr.Header.Get("Date")
50	newmail.From = mr.Header.Get("From")
51	newmail.ReplyTo = mr.Header.Get("Reply-To")
52
53	if err != nil {
54		log.Fatal(err)
55	}
56
57	for {
58		p, err := mr.NextPart()
59		if err == io.EOF {
60			break
61		} else if err != nil {
62			log.Fatal(err)
63		}
64		switch h := p.Header.(type) {
65		case *mail.InlineHeader:
66			ct := strings.Split(p.Header.Get("Content-Type"), ";")[0]
67			b, _ := ioutil.ReadAll(p.Body)
68			part := P{ct: string(b)}
69			newmail.Parts = append(newmail.Parts, part)
70
71		case *mail.AttachmentHeader:
72			filename, _ := h.Filename()
73			log.Printf("Got attachment: %v\n", filename)
74		}
75	}
76
77	j, err := json.Marshal(newmail)
78	if err != nil {
79		log.Fatal(err)
80	}
81	makeReq(j)
82	log.Printf("sent webhook: %v\n", newmail.From)
83}