-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.go
74 lines (65 loc) · 1.9 KB
/
mailer.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
package mail
import (
"github.com/mplewis/gemocities/template"
"github.com/mplewis/gemocities/types"
"github.com/rs/zerolog/log"
)
// templateCache describes a template.Cache.
type templateCache interface {
RenderString(name string, data any) (string, error)
}
// Mailer sends emails using a library of templates.
type Mailer struct {
SMTPArgs
AppDomain string
Templates templateCache
}
// Send sends an email with the given content.
func (m *Mailer) Send(args MailArgs) error {
content, err := args.render(m.Templates)
if err != nil {
return err
}
return Send(m.SMTPArgs, content)
}
func New(cfg types.Config) *Mailer {
sa := SMTPArgs{
Host: cfg.SMTPHost,
Port: cfg.SMTPPort,
Username: cfg.SMTPUsername,
Password: cfg.SMTPPassword,
}
tc := template.Cache{FS: &templates, Prefix: "templates/", Suffix: ".txt"}
log.Info().Str("host", sa.Host).Int("port", sa.Port).Str("username", sa.Username).Msg("Mailer initialized")
return &Mailer{SMTPArgs: sa, Templates: &tc, AppDomain: cfg.AppDomain}
}
// SMTPArgs is the configuration for connecting to an SMTP server.
type SMTPArgs struct {
Host string
Port int
Username string
Password string
}
// MailArgs is the pre-rendered content of an email using a named template.
type MailArgs struct {
From string
To []string
Subject string
Template string
Data any
}
// render renders a MailArgs into a Rendered mail which is ready to send.
func (m *MailArgs) render(tc templateCache) (Rendered, error) {
body, err := tc.RenderString(m.Template, m.Data)
if err != nil {
return Rendered{}, err
}
headers := map[string][]string{"From": []string{m.From}, "To": m.To, "Subject": []string{m.Subject}}
return Rendered{Headers: headers, MimeType: "text/plain", Body: body}, nil
}
// Rendered is the rendered headers and body content of an email.
type Rendered struct {
Headers map[string][]string
MimeType string
Body string
}