This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailgun.go
66 lines (61 loc) · 1.67 KB
/
mailgun.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
package oauth2
import (
"context"
htmltmpl "html/template"
"strings"
texttmpl "text/template"
"github.com/mailgun/mailgun-go/v4"
yall "yall.in"
)
// Mailgun is an implementation of the `emailer` interface that sends mail
// using the Mailgun API.
type Mailgun struct {
From string
Subject string
PlainTextTmpl *texttmpl.Template
HTMLTmpl *htmltmpl.Template
Client *mailgun.MailgunImpl
}
// MailgunTemplateData is the package of data that gets passed to the
// text/template and html/template Execute methods and is available within the
// templates.
type MailgunTemplateData struct {
// The authorization code that needs to be exchanged for a session.
Code string
}
// SendMail sends the specified `code` to the specified `email` using Mailgun's
// API. The mail will have `m.Subject` as a subject and use `m.PlainTextTmpl`
// and `m.HTMLTmpl` as the plain-text and HTML bodies, respectively. The
// templates are given a `MailgunTemplateData` variable as their `data`
// argument.
func (m Mailgun) SendMail(ctx context.Context, email, code string) error {
log := yall.FromContext(ctx)
log = log.WithField("email", email)
var textBody, htmlBody strings.Builder
data := MailgunTemplateData{
Code: code,
}
err := m.PlainTextTmpl.Execute(&textBody, data)
if err != nil {
return err
}
err = m.HTMLTmpl.Execute(&htmlBody, data)
if err != nil {
return err
}
msg := m.Client.NewMessage(
m.From,
m.Subject,
textBody.String(),
email,
)
msg.SetTracking(false)
msg.SetHtml(htmlBody.String())
_, id, err := m.Client.Send(ctx, msg)
if err != nil {
return err
}
log = log.WithField("mailgun_msg_id", id)
log.Debug("sent email")
return nil
}