onasty/mailer/service.go (view raw)
| 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 | slog.ErrorContext(ctx, "failed to send email", |
| 37 | "template_name", templateName, |
| 38 | "err", ctx.Err()) |
| 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 | } |