all repos

onasty @ 7e5389df8b77bcb3308f4586bad32bbdae57c0d2

a one-time notes service

onasty/mailer/service.go (view raw)

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