send email to different targets based on config

This commit is contained in:
Felipe M 2024-11-21 23:16:11 +01:00
parent 326457cca3
commit 4fb0764bcc
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8
5 changed files with 150 additions and 25 deletions

143
main.go
View file

@ -3,22 +3,72 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/mail"
"net/url"
"slices"
"strings"
"time"
"git.nakama.town/fmartingr/gotoolkit/model"
"git.nakama.town/fmartingr/gotoolkit/service"
"github.com/containrrr/shoutrrr"
"github.com/emersion/go-sasl"
"github.com/emersion/go-smtp"
)
type ReceivedEmail struct {
Recipients []string
Msg *mail.Message
body string
}
func (re *ReceivedEmail) String() string {
return fmt.Sprintf(`FROM: %s
TO: %s,
BODY: %s`, re.Msg.Header.Get("From"), re.Recipients, re.Body())
}
func (re *ReceivedEmail) Body() string {
if re.body == "" {
body, err := io.ReadAll(re.Msg.Body)
if err != nil {
slog.Error("failed to read email body", slog.String("err", err.Error()))
}
re.body = string(body)
}
return re.body
}
type Config struct {
Recipients []ConfigRecipient
}
type ConfigRecipient struct {
Addresses []string // email addresses
target string // shoutrrr address
targetURL *url.URL
}
func (cr ConfigRecipient) Target() *url.URL {
if cr.targetURL == nil {
var err error
cr.targetURL, err = url.Parse(cr.target)
if err != nil {
slog.Error("failed to parse shoutrrr target URL", slog.String("target", cr.target), slog.String("err", err.Error()))
}
}
return cr.targetURL
}
var _ model.Server = (*smtpServer)(nil)
type smtpServer struct {
backend *smtp.Server
config Config
}
func (s *smtpServer) IsEnabled() bool {
@ -42,15 +92,51 @@ func NewSMTPServer(backend *smtp.Server) model.Server {
}
// The Backend implements SMTP server methods.
type Backend struct{}
type Backend struct {
config *Config
}
// NewSession is called after client greeting (EHLO, HELO).
func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
return &Session{}, nil
return &Session{
forwarderFunc: bkd.forwardEmail,
}, nil
}
func (bkd *Backend) forwardEmail(email ReceivedEmail) error {
slog.Info("forwading message", slog.String("email", email.String()))
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")},
}
destinationURL := r.Target()
destinationURL.RawQuery = urlParams.Encode()
if err := shoutrrr.Send(destinationURL.String(), email.Body()); err != nil {
slog.Error("Error sending message", slog.String("err", err.Error()))
continue
}
// Already sent via this configuration, go to the next
break
}
}
}
return nil
}
// A Session is returned after successful login.
type Session struct{}
type Session struct {
addresses []string
body string
forwarderFunc func(ReceivedEmail) error
}
// AuthMechanisms returns a slice of available auth mechanisms; only PLAIN is
// supported in this example.
@ -69,20 +155,32 @@ func (s *Session) Auth(mech string) (sasl.Server, error) {
}
func (s *Session) Mail(from string, opts *smtp.MailOptions) error {
log.Println("Mail from:", from, opts)
slog.Debug("Mail from", slog.String("from", from))
return nil
}
func (s *Session) Rcpt(to string, opts *smtp.RcptOptions) error {
log.Println("Rcpt to:", to)
slog.Debug("Rcpt to", slog.String("to", to))
s.addresses = append(s.addresses, to)
return nil
}
func (s *Session) Data(r io.Reader) error {
_, err := http.Post("https://ntfy.sh/fmartingr-dev", "text/plain", r)
msg, err := mail.ReadMessage(r)
if err != nil {
slog.Error("Error sending message:", slog.String("err", err.Error()))
slog.Error("Error reading data", slog.String("err", err.Error()))
return fmt.Errorf("Error reading data: %w", err)
}
slog.Info("Received email", slog.String("destination", strings.Join(s.addresses, ",")))
if err := s.forwarderFunc(ReceivedEmail{
Recipients: s.addresses,
Msg: msg,
}); err != nil {
slog.Error("Error forwarding email", slog.String("err", err.Error()))
}
return nil
}
@ -92,21 +190,20 @@ func (s *Session) Logout() error {
return nil
}
// ExampleServer runs an example SMTP server.
//
// It can be tested manually with e.g. netcat:
//
// > netcat -C localhost 1025
// EHLO localhost
// AUTH PLAIN
// AHVzZXJuYW1lAHBhc3N3b3Jk
// MAIL FROM:<root@nsa.gov>
// RCPT TO:<root@gchq.gov.uk>
// DATA
// Hey <3
// .
func main() {
be := &Backend{}
config := &Config{
Recipients: []ConfigRecipient{{
Addresses: []string{"test@fmartingr.com", "caca@caca.com"},
target: "ntfy://ntfy.sh/fmartingr-dev",
}, {
Addresses: []string{"something@something.com"},
target: "ntfy://ntfy.sh/fmartingr-dev",
}},
}
be := &Backend{
config: config,
}
smtpBackend := smtp.NewServer(be)