-
Notifications
You must be signed in to change notification settings - Fork 3
/
email.go
86 lines (67 loc) · 2.13 KB
/
email.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
package main
import (
"bytes"
"fmt"
"html/template"
"net/mail"
"net/smtp"
"github.com/BurntSushi/toml"
)
type EmailReleaseHandlerConfig struct {
SmtpServer string `toml:"smtp_server"`
SmtpPort int `toml:"smtp_port"`
SmtpUsername string `toml:"smtp_username"`
SmtpPassword string `toml:"smtp_password"`
From string `toml:"from"`
To string `toml:"to"`
Template string `toml:"template"`
}
type EmailReleaseHandler struct {
smtpServer string
smtpPort int
smtpAuth smtp.Auth
from *mail.Address
to *mail.Address
template *template.Template
}
func (handler EmailReleaseHandler) Handle(app *App, notification HockeyNotification) error {
var err error
contents := new(bytes.Buffer)
contents.Write([]byte(fmt.Sprintf("To: %s\r\n", handler.to)))
contents.Write([]byte(fmt.Sprintf("From: %s\r\n", handler.from)))
contents.Write([]byte(fmt.Sprintf("Subject: %s - %s\r\n", notification.AppVersion.Title, notification.AppVersion.ShortVersion)))
contents.Write([]byte("Content-Type: text/html; charset=UTF-8\r\n"))
contents.Write([]byte("\r\n"))
if err = handler.template.Execute(contents, notification); err != nil {
return err
}
if err = smtp.SendMail(fmt.Sprintf("%s:%d", handler.smtpServer, handler.smtpPort),
handler.smtpAuth, handler.from.Address, []string{handler.to.Address},
contents.Bytes()); err != nil {
return err
}
return nil
}
func NewEmailReleaseHandler(configPrimitive toml.Primitive) (NotificationHandler, error) {
var err error
var config EmailReleaseHandlerConfig
if err = toml.PrimitiveDecode(configPrimitive, &config); err != nil {
return nil, err
}
auth := smtp.PlainAuth("", config.SmtpUsername, config.SmtpPassword, config.SmtpServer)
var template *template.Template
if template, err = template.ParseFiles(config.Template); err != nil {
return nil, err
}
var (
to *mail.Address
from *mail.Address
)
if to, err = mail.ParseAddress(config.To); err != nil {
return nil, err
}
if from, err = mail.ParseAddress(config.From); err != nil {
return nil, err
}
return &EmailReleaseHandler{config.SmtpServer, config.SmtpPort, auth, from, to, template}, nil
}