all repos

onasty @ c3cd6686a990dcd8870c4f1db6073bb495b66842

a one-time notes service

onasty/mailer/service.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
50
51
package main

import (
	"context"
	"log/slog"
)

type Service struct {
	appURL      string
	frontendURL string

	mg *Mailgun
}

func NewService(appURL, frontendURL string, mg *Mailgun) *Service {
	return &Service{
		appURL:      appURL,
		frontendURL: frontendURL,
		mg:          mg,
	}
}

func (s Service) Send(
	ctx context.Context,
	cancel context.CancelFunc,
	receiver, templateName string,
	templateOpts map[string]string,
) error {
	tmpl, err := getTemplate(s.appURL, s.frontendURL, templateName)
	if err != nil {
		return err
	}

	t := tmpl(templateOpts)

	go func() {
		select {
		case <-ctx.Done():
			return
		default:
			if err := s.mg.Send(ctx, receiver, t.Subject, t.Body); err != nil {
				slog.ErrorContext(ctx, "failed to send email",
					"template_name", templateName,
					"err", err)
			}
			cancel()
		}
	}()

	return nil
}