all repos

onasty @ 7ff621d

a one-time notes service

onasty/mailer/service.go (view raw)

Olexandr Smirnov Olexandr Smirnov
ss2316544@gmail.com
web: forgot password (#169)..., 10 months ago
1
package main
2
3
import (
4
	"context"
5
	"log/slog"
6
)
7
8
type Service struct {
9
	appURL      string
10
	frontendURL string
11
12
	mg *Mailgun
13
}
14
15
func NewService(appURL, frontendURL string, mg *Mailgun) *Service {
16
	return &Service{
17
		appURL:      appURL,
18
		frontendURL: frontendURL,
19
		mg:          mg,
20
	}
21
}
22
23
func (s Service) Send(
24
	ctx context.Context,
25
	cancel context.CancelFunc,
26
	receiver, templateName string,
27
	templateOpts map[string]string,
28
) error {
29
	tmpl, err := getTemplate(s.appURL, s.frontendURL, templateName)
30
	if err != nil {
31
		return err
32
	}
33
34
	t := tmpl(templateOpts)
35
36
	go func() {
37
		select {
38
		case <-ctx.Done():
39
			return
40
		default:
41
			if err := s.mg.Send(ctx, receiver, t.Subject, t.Body); err != nil {
42
				slog.ErrorContext(ctx, "failed to send email",
43
					"template_name", templateName,
44
					"err", err)
45
			}
46
			cancel()
47
		}
48
	}()
49
50
	return nil
51
}