-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailer.go
More file actions
80 lines (68 loc) · 1.5 KB
/
mailer.go
File metadata and controls
80 lines (68 loc) · 1.5 KB
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
package wildlifenl
import (
"bytes"
"log"
"text/template"
"time"
_ "embed"
"github.com/go-mail/mail"
)
const (
emailSubject = "Aanmelden bij WildlifeNL"
)
var (
//go:embed templates/email.go.tmpl
emailTemplateFS string
emailTemplate *template.Template
)
func init() {
emailTemplate = template.Must(template.New("email").Parse(emailTemplateFS))
}
type mailData struct {
AppName string
DisplayName string
Code string
Year int
}
type Mailer struct {
config *Configuration
}
func newMailer(config *Configuration) *Mailer {
return &Mailer{config: config}
}
func (e *Mailer) Ping() error {
if e.config.EmailHost == "no-email" {
return nil
}
s, err := e.dailer().Dial()
if err != nil {
return err
}
return s.Close()
}
func (e *Mailer) SendCode(appName, displayName, email, code string) error {
if e.config.EmailHost == "no-email" {
log.Println("Code for", email, "is:", code)
return nil
}
var bodyBuffer bytes.Buffer
err := emailTemplate.Execute(&bodyBuffer, mailData{
AppName: appName,
DisplayName: displayName,
Code: code,
Year: time.Now().Year(),
})
if err != nil {
return err
}
body := bodyBuffer.String()
m := mail.NewMessage()
m.SetHeader("From", e.config.EmailFrom)
m.SetHeader("To", email)
m.SetHeader("Subject", emailSubject)
m.SetBody("text/html", body)
return e.dailer().DialAndSend(m)
}
func (e *Mailer) dailer() *mail.Dialer {
return mail.NewDialer(e.config.EmailHost, 587, e.config.EmailUser, e.config.EmailPassword)
}