From a2b696471ce0aeee1610ca11513b742d5f2877e0 Mon Sep 17 00:00:00 2001 From: "Felipe M. (aider)" Date: Mon, 2 Dec 2024 16:30:43 +0100 Subject: [PATCH] feat: Add catch-all recipient support for unmatched email addresses --- backend.go | 55 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/backend.go b/backend.go index ddcf792..ce529e3 100644 --- a/backend.go +++ b/backend.go @@ -18,6 +18,28 @@ type Backend struct { config *Config } +func (bkd *Backend) sendNotification(recipient ConfigRecipient, email ReceivedEmail) error { + urlParams := url.Values{ + "title": {email.Msg.Header.Get("Subject")}, + } + + destinationURL := recipient.GetTargetURL() + destinationURL.RawQuery = urlParams.Encode() + + body, err := email.Body() + if err != nil { + slog.Error("Error getting email body", slog.String("err", err.Error())) + return fmt.Errorf("failed to get email body: %w", err) + } + + if err := shoutrrr.Send(destinationURL.String(), body); err != nil { + slog.Error("Error sending message", slog.String("err", err.Error())) + return fmt.Errorf("failed to send notification: %w", err) + } + + return nil +} + func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) { return &Session{ forwarderFunc: bkd.forwardEmail, @@ -28,30 +50,29 @@ func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) { func (bkd *Backend) forwardEmail(email ReceivedEmail) error { slog.Info("forwading message", slog.String("to", strings.Join(email.Recipients, ","))) + // Try to match configured recipients first + matched := false for _, r := range bkd.config.Recipients { for _, a := range email.Recipients { if slices.Contains(r.Addresses, a) { - urlParams := url.Values{ - "title": {email.Msg.Header.Get("Subject")}, + if err := bkd.sendNotification(r, email); err != nil { + return err } - - destinationURL := r.GetTargetURL() - destinationURL.RawQuery = urlParams.Encode() - - body, err := email.Body() - if err != nil { - slog.Error("Error getting email body", slog.String("err", err.Error())) - continue - } - - if err := shoutrrr.Send(destinationURL.String(), body); err != nil { - slog.Error("Error sending message", slog.String("err", err.Error())) - continue - } - + matched = true break } } + if matched { + break + } + } + + // If no recipient matched and catch-all is configured, use it + if !matched && bkd.config.CatchAll != nil { + slog.Info("using catch-all recipient for unmatched email") + if err := bkd.sendNotification(*bkd.config.CatchAll, email); err != nil { + return err + } } return nil