-
Notifications
You must be signed in to change notification settings - Fork 0
/
email.go
64 lines (52 loc) · 1.14 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
package email
import (
"fmt"
"log"
"net/smtp"
"os"
"github.com/cswank/store/internal/config"
)
var (
cfg config.Config
mailTemplate = `From: %s
To: %s
Subject: %s
%s
`
Send func(Msg) error
)
type Msg struct {
Name string `schema:"name"`
From string `schema:"from"`
To string `schema:"to"`
Subject string `schema:"subject"`
Body string `schema:"body"`
}
func Init(c config.Config) {
cfg = c
if cfg.Email == "" || cfg.EmailPassword == "" {
log.Println("warning: STORE_EMAIL or STORE_EMAIL_PASSWORD not set, using fake email (writes to /tmp/mail.txt)")
Send = sendFake
} else {
Send = sendEmail
}
}
func sendEmail(msg Msg) error {
text := fmt.Sprintf(mailTemplate, msg.From, msg.To, msg.Subject, msg.Body)
return smtp.SendMail(
"smtp.gmail.com:587",
smtp.PlainAuth("", cfg.Email, cfg.EmailPassword, "smtp.gmail.com"),
cfg.Email,
[]string{msg.To}, []byte(text),
)
}
func sendFake(msg Msg) error {
text := fmt.Sprintf(mailTemplate, msg.From, msg.To, msg.Subject, msg.Body)
f, err := os.Create("/tmp/mail.txt")
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(text)
return err
}