-
Notifications
You must be signed in to change notification settings - Fork 57
/
mail.go
85 lines (70 loc) · 1.68 KB
/
mail.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
package mail
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strconv"
"github.com/liam-lai/ptt-alertor/myutil"
"github.com/liam-lai/ptt-alertor/ptt/article"
"gopkg.in/mailgun/mailgun-go.v1"
)
type Mail struct {
Title
Body
Receiver string
}
type Title struct {
BoardName string
Keyword string
articleQuantity int
}
type Body struct {
Articles []article.Article
}
func (title Title) String() string {
return "[PTTAlertor] 在 " + title.BoardName + " 版有 " + strconv.Itoa(title.articleQuantity) + " 篇關於「" + title.Keyword + "」的文章發表"
}
func (body Body) String() string {
var content string
for _, article := range body.Articles {
content += article.Title + "\r\n" +
"https://www.ptt.cc" + article.Link + "\r\n" +
"\r\n"
}
return content + "Send From PTT Alertor"
}
func (mail Mail) Send() {
mg := newMailgun()
mail.articleQuantity = len(mail.Body.Articles)
message := mailgun.NewMessage(
"PttAlertor@mg.dinolai.com",
mail.Title.String(),
mail.Body.String(),
mail.Receiver)
resp, id, err := mg.Send(message)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID: %s Resp: %s\n", id, resp)
}
func newMailgun() mailgun.Mailgun {
config := readConfig()
domain := config["domain"]
apiKey := config["apiKey"]
publicAPIKey := config["publicAPIKey"]
return mailgun.NewMailgun(domain, apiKey, publicAPIKey)
}
func readConfig() map[string]string {
projectRoot := myutil.ProjectRootPath()
mailgunConfigJSON, err := ioutil.ReadFile(projectRoot + "/config/mailgun.json")
if err != nil {
log.Fatal(err)
}
var config map[string]string
err = json.Unmarshal(mailgunConfigJSON, &config)
if err != nil {
log.Fatal(err)
}
return config
}