Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat: add dry run mode to validate the request without sending
Jonas Kaninda1b6097023a47
diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.goindex 6b26194..c9c4461 100644--- a/internal/handlers/email_handler.go+++ b/internal/handlers/email_handler.go@@ -45,13 +45,16 @@ type EmailHandler struct {settings *settings.Provider}type SendEmailRequest struct {- Body email.SendRequest `json:"body"`+ DryRun bool `query:"dry_run" doc:"Validate the request without sending"`+ Body email.SendRequest `json:"body"`}type SendTemplateEmailRequest struct {- Body email.SendTemplateRequest `json:"body"`+ DryRun bool `query:"dry_run"`+ Body email.SendTemplateRequest `json:"body"`}type SendBatchEmailRequest struct {- Body email.BatchRequest `json:"body"`+ DryRun bool `query:"dry_run" doc:"Validate the request without sending"`+ Body email.BatchRequest `json:"body"`}type ListRequest struct {Page int `query:"page" default:"0"`@@ -98,9 +101,13 @@ func redactEmails(emails []models.Email) {func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {userID := c.GetInt("user_id")- apiKeyID := c.GetInt("api_key_id")userEmail := c.GetString("user_email")+ if req.DryRun {+ return h.handleDryRun(c, userID, userEmail, req)+ }++ apiKeyID := c.GetInt("api_key_id")resp, err := h.service.Send(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)if err != nil {if isRateLimitError(err) {@@ -125,11 +132,39 @@ func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {return ok(c, resp)}+func (h *EmailHandler) handleDryRun(c *okapi.Context, userID int, userEmail string, req *SendEmailRequest) error {+ resp, err := h.service.ValidateSend(c.Request().Context(), uint(userID), userEmail, &req.Body)+ if err != nil {+ if isRateLimitError(err) {+ return c.AbortTooManyRequests(err.Error())+ }+ if isDomainVerificationError(err) {+ return c.AbortForbidden(err.Error())+ }+ return c.AbortBadRequest(err.Error())+ }+ return ok(c, resp)+}+func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailRequest) error {userID := c.GetInt("user_id")- apiKeyID := c.GetInt("api_key_id")userEmail := c.GetString("user_email")+ if req.DryRun {+ resp, err := h.service.ValidateSendWithTemplate(c.Request().Context(), uint(userID), userEmail, &req.Body)+ if err != nil {+ if isRateLimitError(err) {+ return c.AbortTooManyRequests(err.Error())+ }+ if isDomainVerificationError(err) {+ return c.AbortForbidden(err.Error())+ }+ return c.AbortBadRequest(err.Error())+ }+ return ok(c, resp)+ }++ apiKeyID := c.GetInt("api_key_id")resp, err := h.service.SendWithTemplate(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)if err != nil {if isRateLimitError(err) {@@ -155,9 +190,20 @@ func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailfunc (h *EmailHandler) SendBatch(c *okapi.Context, req *SendBatchEmailRequest) error {userID := c.GetInt("user_id")- apiKeyID := c.GetInt("api_key_id")userEmail := c.GetString("user_email")+ if req.DryRun {+ resp, err := h.service.ValidateSendBatch(c.Request().Context(), uint(userID), userEmail, &req.Body)+ if err != nil {+ if isRateLimitError(err) {+ return c.AbortTooManyRequests(err.Error())+ }+ return c.AbortBadRequest(err.Error())+ }+ return ok(c, resp)+ }++ apiKeyID := c.GetInt("api_key_id")resp, err := h.service.SendBatch(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)if err != nil {if isRateLimitError(err) {diff --git a/internal/services/email/service.go b/internal/services/email/service.goindex f39c09a..0520c3e 100644--- a/internal/services/email/service.go+++ b/internal/services/email/service.go@@ -190,6 +190,145 @@ type BatchResult struct {Error string `json:"error,omitempty"`}+// DryRunResponse is returned when a send request is validated without actually sending.+type DryRunResponse struct {+ Valid bool `json:"valid"`+ From string `json:"from"`+ To []string `json:"to"`+ Subject string `json:"subject"`+ Recipients int `json:"recipients"`+ SuppressedCount int `json:"suppressed_count"`+ AttachmentCount int `json:"attachment_count"`+ HasHTML bool `json:"has_html"`+ HasText bool `json:"has_text"`+ RenderedSubject string `json:"rendered_subject,omitempty"`+}++// ValidateSend runs all validation checks without persisting or sending.+func (s *Service) ValidateSend(ctx context.Context, userID uint, userEmail string, req *SendRequest) (*DryRunResponse, error) {+ if s.settings != nil && s.settings.MaintenanceMode() {+ return nil, fmt.Errorf("maintenance: email sending is temporarily disabled")+ }++ if err := s.limiter.Check(ctx, userEmail); err != nil {+ return nil, fmt.Errorf("rate_limit: %w", err)+ }++ if len(req.Attachments) > 0 {+ maxSize := DefaultMaxAttachmentSize+ if s.settings != nil {+ maxSize = int64(s.settings.MaxAttachmentSizeMB()) * 1024 * 1024+ }+ if err := ValidateAttachments(req.Attachments, maxSize, DefaultMaxTotalSize); err != nil {+ return nil, fmt.Errorf("attachment validation: %w", err)+ }+ }++ if err := s.checkDomainVerification(userID, req.From); err != nil {+ return nil, err+ }++ activeRecipients := req.To+ suppressedCount := 0+ if s.suppressionRepo != nil {+ filtered, err := s.suppressionRepo.FilterSuppressed(userID, req.To)+ if err != nil {+ return nil, fmt.Errorf("failed to check suppression list: %w", err)+ }+ suppressedCount = len(req.To) - len(filtered)+ activeRecipients = filtered+ }++ return &DryRunResponse{+ Valid: true,+ From: req.From,+ To: activeRecipients,+ Subject: req.Subject,+ Recipients: len(activeRecipients),+ SuppressedCount: suppressedCount,+ AttachmentCount: len(req.Attachments),+ HasHTML: req.HTML != "",+ HasText: req.Text != "",+ }, nil+}++// ValidateSendWithTemplate validates a template send request without sending.+func (s *Service) ValidateSendWithTemplate(ctx context.Context, userID uint, userEmail string, req *SendTemplateRequest) (*DryRunResponse, error) {+ tmpl, err := s.templateRepo.FindByName(userID, req.Template)+ if err != nil {+ return nil, fmt.Errorf("template not found: %s", req.Template)+ }++ rendered, err := s.resolveAndRender(tmpl, req.Language, req.TemplateData)+ if err != nil {+ return nil, fmt.Errorf("failed to render template: %w", err)+ }++ from := req.From+ if from == "" {+ from = defaultFromAddress+ }++ resp, err := s.ValidateSend(ctx, userID, userEmail, &SendRequest{+ From: from,+ To: req.To,+ Subject: rendered.Subject,+ HTML: rendered.HTML,+ Text: rendered.Text,+ Attachments: req.Attachments,+ })+ if err != nil {+ return nil, err+ }+ resp.RenderedSubject = rendered.Subject+ return resp, nil+}++// ValidateSendBatch validates a batch send request without sending.+func (s *Service) ValidateSendBatch(ctx context.Context, userID uint, userEmail string, req *BatchRequest) (*DryRunResponse, error) {+ if s.settings != nil {+ maxBatch := s.settings.MaxBatchSize()+ if maxBatch > 0 && len(req.Recipients) > maxBatch {+ return nil, fmt.Errorf("batch size %d exceeds maximum allowed (%d)", len(req.Recipients), maxBatch)+ }+ }++ _, err := s.templateRepo.FindByName(userID, req.Template)+ if err != nil {+ return nil, fmt.Errorf("template not found: %s", req.Template)+ }++ from := req.From+ if from == "" {+ from = defaultFromAddress+ }++ emails := make([]string, len(req.Recipients))+ for i, r := range req.Recipients {+ emails[i] = r.Email+ }++ activeRecipients := emails+ suppressedCount := 0+ if s.suppressionRepo != nil {+ filtered, err := s.suppressionRepo.FilterSuppressed(userID, emails)+ if err != nil {+ return nil, fmt.Errorf("failed to check suppression list: %w", err)+ }+ suppressedCount = len(emails) - len(filtered)+ activeRecipients = filtered+ }++ return &DryRunResponse{+ Valid: true,+ From: from,+ To: activeRecipients,+ Subject: req.Template,+ Recipients: len(activeRecipients),+ SuppressedCount: suppressedCount,+ }, nil+}+func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, userEmail string, req *SendRequest) (*SendResponse, error) {// Enforce maintenance modeif s.settings != nil && s.settings.MaintenanceMode() {diff --git a/internal/services/ratelimit/redis_limiter.go b/internal/services/ratelimit/redis_limiter.goindex e763453..bbec0e2 100644--- a/internal/services/ratelimit/redis_limiter.go+++ b/internal/services/ratelimit/redis_limiter.go@@ -100,6 +100,32 @@ func (l *RedisLimiter) Allow(ctx context.Context, userEmail string) error {return nil}+// Check verifies the user is within rate limits without incrementing the counters.+func (l *RedisLimiter) Check(ctx context.Context, userEmail string) error {+ hourlyLimit, dailyLimit := l.effectiveLimits()++ hourKey := fmt.Sprintf("ratelimit:hour:%s:%s", userEmail, time.Now().Format("2006010215"))+ dayKey := fmt.Sprintf("ratelimit:day:%s:%s", userEmail, time.Now().Format("20060102"))++ hourCount, err := l.client.Get(ctx, hourKey).Int64()+ if err != nil && err != redis.Nil {+ return fmt.Errorf("rate limit check failed: %w", err)+ }+ if hourCount >= int64(hourlyLimit) {+ return fmt.Errorf("hourly rate limit exceeded (%d/%d)", hourCount, hourlyLimit)+ }++ dayCount, err := l.client.Get(ctx, dayKey).Int64()+ if err != nil && err != redis.Nil {+ return fmt.Errorf("rate limit check failed: %w", err)+ }+ if dayCount >= int64(dailyLimit) {+ return fmt.Errorf("daily rate limit exceeded (%d/%d)", dayCount, dailyLimit)+ }++ return nil+}+// AllowLogin checks if a login attempt from the given IP is within rate limits.// The max attempts and window duration are configurable via admin settings.func (l *RedisLimiter) AllowLogin(ctx context.Context, ip string) error {