|
package smtpsrv |
|
|
|
import ( |
|
"context" |
|
"fmt" |
|
"log/slog" |
|
"net" |
|
"strings" |
|
"time" |
|
|
|
"github.com/emersion/go-smtp" |
|
) |
|
|
|
|
|
type SMTPLogger struct { |
|
logger *slog.Logger |
|
} |
|
|
|
|
|
func (l *SMTPLogger) Printf(format string, v ...interface{}) { |
|
s := fmt.Sprintf(format, v...) |
|
|
|
|
|
if strings.Contains(s, "read: connection reset by peer") { |
|
return |
|
} |
|
l.logger.Error("SMTP error.", slog.String("error", s)) |
|
} |
|
|
|
|
|
func (l *SMTPLogger) Println(v ...interface{}) { |
|
s := fmt.Sprint(v...) |
|
|
|
|
|
if strings.Contains(s, "read: connection reset by peer") { |
|
return |
|
} |
|
l.logger.Error("SMTP error.", slog.String("error", s)) |
|
} |
|
|
|
|
|
type Server struct { |
|
cfg Config |
|
srv *smtp.Server |
|
} |
|
|
|
|
|
func NewServer(cfg Config) *Server { |
|
s := &Server{cfg: cfg} |
|
|
|
srv := smtp.NewServer(s) |
|
srv.ErrorLog = &SMTPLogger{logger: cfg.Logger} |
|
srv.Domain = cfg.Domain |
|
srv.ReadTimeout = 10 * time.Second |
|
srv.WriteTimeout = 10 * time.Second |
|
srv.TLSConfig = cfg.TLSConfig |
|
s.srv = srv |
|
|
|
if cfg.MaxRecipients == 0 { |
|
cfg.MaxRecipients = 1 |
|
} |
|
if cfg.BackgroundContext == nil { |
|
panic("smtpsrv: BackgroundContext is required") |
|
} |
|
if cfg.AuthorizeFunc == nil { |
|
panic("smtpsrv: AuthorizeFunc is required") |
|
} |
|
if cfg.CreateAlertFunc == nil { |
|
panic("smtpsrv: CreateAlertFunc is required") |
|
} |
|
|
|
return s |
|
} |
|
|
|
var _ smtp.Backend = &Server{} |
|
|
|
|
|
func (s *Server) ServeSMTP(l net.Listener) error { return s.srv.Serve(l) } |
|
|
|
|
|
func (s *Server) NewSession(_ *smtp.Conn) (smtp.Session, error) { return &Session{cfg: s.cfg}, nil } |
|
|
|
|
|
func (s *Server) Shutdown(ctx context.Context) error { return s.srv.Shutdown(ctx) } |
|
|