all repos

onasty @ 5bdd1f8

a one-time notes service

onasty/mailer/mailgun.go(view raw)

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
package main

import (
	"context"
	"log/slog"

	"github.com/mailgun/mailgun-go/v4"
	"github.com/olexsmir/onasty/internal/transport/http/reqid"
)

type Mailer interface {
	Send(ctx context.Context, to, subject, content string) error
}

var _ Mailer = (*Mailgun)(nil)

type Mailgun struct {
	from string

	mg *mailgun.MailgunImpl
}

func NewMailgun(from, domain, apiKey string) *Mailgun {
	mg := mailgun.NewMailgun(domain, apiKey)
	return &Mailgun{
		from: from,
		mg:   mg,
	}
}

func (m *Mailgun) Send(ctx context.Context, to, subject, content string) error {
	msg := mailgun.NewMessage(m.from, subject, "", to)
	msg.SetHTML(content)

	slog.InfoContext(ctx, "email sent", "to", to)

	_, _, err := m.mg.Send(ctx, msg)
	if err != nil {
		RecordEmailFailed(reqid.GetContext(ctx))
		return err
	}

	slog.DebugContext(ctx, "email sent", "subject", subject, "content", content, "err", err)
	slog.InfoContext(ctx, "email sent", "to", to)

	RecordEmailSent()

	return nil
}