feat: Add catch-all recipient support for unmatched email addresses

This commit is contained in:
Felipe M 2024-12-02 16:30:43 +01:00
parent cfebaf09e3
commit a2b696471c
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8

View file

@ -18,6 +18,28 @@ type Backend struct {
config *Config 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) { func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
return &Session{ return &Session{
forwarderFunc: bkd.forwardEmail, forwarderFunc: bkd.forwardEmail,
@ -28,30 +50,29 @@ func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
func (bkd *Backend) forwardEmail(email ReceivedEmail) error { func (bkd *Backend) forwardEmail(email ReceivedEmail) error {
slog.Info("forwading message", slog.String("to", strings.Join(email.Recipients, ","))) 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 _, r := range bkd.config.Recipients {
for _, a := range email.Recipients { for _, a := range email.Recipients {
if slices.Contains(r.Addresses, a) { if slices.Contains(r.Addresses, a) {
urlParams := url.Values{ if err := bkd.sendNotification(r, email); err != nil {
"title": {email.Msg.Header.Get("Subject")}, return err
} }
matched = true
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
}
break 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 return nil