generated from ricoberger/go-vue-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.go
executable file
·96 lines (80 loc) · 2.24 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
86
87
88
89
90
91
92
93
94
95
96
package mail
import (
"bytes"
"html/template"
"net/smtp"
"github.com/jamieroyce/vue-golang/pkg/static"
)
// Config represents the mail configuration
type Config struct {
Identity string `yaml:"identity"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Addr string `yaml:"addr"`
From string `yaml:"from"`
HTML bool `yaml:"html"`
Subjects map[string]string `yaml:"subjects"`
}
// Client implements a mail client
type Client struct {
auth smtp.Auth
addr string
from string
html bool
subjects map[string]string
}
// NewClient return a new mail
func NewClient(config *Config) *Client {
return &Client{
auth: smtp.PlainAuth(config.Identity, config.Username, config.Password, config.Host),
addr: config.Addr,
from: config.From,
html: config.HTML,
subjects: config.Subjects,
}
}
// Send sends an email message to the provided address and with the provided subject
func (c *Client) Send(to, email string, data interface{}) error {
var mime string
var templateFile string
if c.html {
mime = "MIME-version: 1.0;\r\nContent-Type: text/html; charset=\"UTF-8\";\r\n\r\n"
templateFile = "/web/mail/" + email + ".html"
} else {
mime = "MIME-version: 1.0;\r\nContent-Type: text/plain; charset=\"UTF-8\";\r\n\r\n"
templateFile = "/web/mail/" + email + ".txt"
}
subject := "Subject: " + c.subjects[email] + "\r\n"
fromHeader := "From: " + c.from + "\r\n"
toHeader := "To: " + to + "\r\n"
body, err := c.parseTemplate(templateFile, data)
if err != nil {
return err
}
msg := []byte(subject + fromHeader + toHeader + mime + "\r\n" + body)
err = smtp.SendMail(
c.addr,
c.auth,
c.from,
[]string{to},
[]byte(msg),
)
return err
}
// parseTemplate parses a html template file
func (c *Client) parseTemplate(templateFile string, data interface{}) (string, error) {
file, err := static.FSString(false, templateFile)
if err != nil {
return "", err
}
t, err := template.New(templateFile).Parse(file)
if err != nil {
return "", err
}
buffer := new(bytes.Buffer)
if err = t.Execute(buffer, data); err != nil {
return "", err
}
return buffer.String(), nil
}