-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.go
94 lines (83 loc) · 2.6 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (c) 2019, Mohlmann Solutions SRL. All rights reserved.
// Use of this source code is governed by a License that can be found in the LICENSE file.
// SPDX-License-Identifier: BSD-3-Clause
//Package mailer is a functional wrapper around the standard "net/smtp" and "html/template" packages.
package mailer
import (
"bytes"
"fmt"
"html/template"
"log"
"net/smtp"
"strings"
"time"
)
const (
// GlobalHeaders is set on every message.
GlobalHeaders = "MIME-Version: 1.0\r\nContent-type: text/html; charset=\"UTF-8\"\r\n\r\n"
)
// Debug mode prints the outgoing mail before sending
var Debug bool
// Header for mail message
type Header struct {
Key string
Values []string
}
func (h Header) String() string {
if h.Values == nil {
return ""
}
return fmt.Sprintf(
"%s: %s\r\n",
strings.Title(h.Key),
strings.Join(h.Values, ","),
)
}
func mailHeaders(headers []Header) *bytes.Buffer {
var msg bytes.Buffer
for _, h := range headers {
msg.WriteString(h.String())
}
msg.WriteString(GlobalHeaders)
return &msg
}
// Mailer holds a html template, server and authentication information for efficient reuse.
type Mailer struct {
tmpl *template.Template
addr string
from string
auth smtp.Auth
}
// New returns a reusable mailer.
// Tmpl should hold a collection of parsed templates.
// Addr is the hostname and port used by smtp.SendMail. For example:
// "mail.host.com:587"
// From is used in every subsequent SendMail invocation and set as message header.
// If auth is nil, connections will omit authentication.
func New(tmpl *template.Template, addr, from string, auth smtp.Auth) *Mailer {
return &Mailer{tmpl, addr, from, auth}
}
// Send renders the headers and named template with passed data.
// The rendered message is sent using smtp.SendMail, to all the recipients.
//
// Headers keys are rendered Title cased, and the values are joined with a comma separator.
// Each entry becomes a CRLF separated line. For example:
// {"to", []string{"[email protected]", "[email protected]"}}
// Results in:
//
// The current time is automatically appended as timestamp header.
func (m *Mailer) Send(headers []Header, tmplName string, data interface{}, recipients ...string) error {
headers = append(headers,
Header{"from", []string{m.from}},
Header{"date", []string{time.Now().Format(time.RFC822Z)}},
)
msg := mailHeaders(headers)
if err := m.tmpl.ExecuteTemplate(msg, tmplName, data); err != nil {
return err
}
if Debug {
log.Printf("mailer: %+v;\n------------\n%s", m, msg)
}
return smtp.SendMail(m.addr, m.auth, m.from, recipients, msg.Bytes())
}