Files
Memoh/internal/handlers/email_webhook.go
T
BBQ cc5f00355f feat: add email service with multi-adapter support (#146)
* feat: add email service with multi-adapter support

Implement a full-stack email service with global provider management,
per-bot bindings with granular read/write permissions, outbox audit
storage, and MCP tool integration for direct mailbox access.

Backend:
- Email providers: CRUD with dynamic config schema (generic SMTP/IMAP, Mailgun)
- Generic adapter: go-mail (SMTP) + go-imap/v2 (IMAP IDLE real-time push via
  UnilateralDataHandler + UID-based tracking + periodic check fallback)
- Mailgun adapter: mailgun-go/v5 with dual inbound mode (webhook + poll)
- Bot email bindings: per-bot provider binding with independent r/w permissions
- Outbox: outbound email audit log with status tracking
- Trigger: inbound emails push notification to bot_inbox (from/subject only,
  LLM reads full content on demand via MCP tools)
- MailboxReader interface: on-demand IMAP queries for listing/reading emails
- MCP tools: email_accounts, email_send, email_list (paginated mailbox),
  email_read (by UID) — all with multi-binding and provider_id selection
- Webhook: /email/mailgun/webhook/:config_id (JWT-skipped, signature-verified)
- DB migration: 0019_add_email (email_providers, bot_email_bindings, email_outbox)

Frontend:
- Email Providers page: /email-providers with MasterDetailSidebarLayout
- Dynamic config form rendered from ordered provider meta schema with i18n keys
- Bot detail: Email tab with bindings management + outbox audit table
- Sidebar navigation entry
- Full i18n support (en + zh)
- Auto-generated SDK from Swagger

Closes #17

* feat(email): trigger bot conversation immediately on inbound email

Instead of only storing an inbox item and waiting for the next chat,
the email trigger now proactively invokes the conversation resolver
so the bot processes new emails right away — aligned with the
schedule/heartbeat trigger pattern.

* fix: lint

---------

Co-authored-by: Acbox <acbox0328@gmail.com>
2026-02-28 21:03:59 +08:00

93 lines
3.0 KiB
Go

package handlers
import (
"encoding/json"
"log/slog"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/memohai/memoh/internal/email"
emailmailgun "github.com/memohai/memoh/internal/email/adapters/mailgun"
)
// EmailWebhookHandler handles inbound email webhooks (Mailgun).
// Modeled after the Feishu WebhookHandler pattern.
type EmailWebhookHandler struct {
service *email.Service
manager *email.Manager
trigger *email.Trigger
logger *slog.Logger
}
func NewEmailWebhookHandler(log *slog.Logger, service *email.Service, manager *email.Manager, trigger *email.Trigger) *EmailWebhookHandler {
return &EmailWebhookHandler{
service: service,
manager: manager,
trigger: trigger,
logger: log.With(slog.String("handler", "email_webhook")),
}
}
func (h *EmailWebhookHandler) Register(e *echo.Echo) {
e.POST("/email/mailgun/webhook/:config_id", h.HandleMailgun)
}
// HandleMailgun godoc
// @Summary Mailgun inbound email webhook
// @Description Receives inbound emails from Mailgun
// @Tags email-webhook
// @Param config_id path string true "Email provider config ID"
// @Success 200 {object} map[string]string
// @Failure 400 {object} ErrorResponse
// @Failure 403 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /email/mailgun/webhook/{config_id} [post]
func (h *EmailWebhookHandler) HandleMailgun(c echo.Context) error {
configID := strings.TrimSpace(c.Param("config_id"))
if configID == "" {
return echo.NewHTTPError(http.StatusBadRequest, "config_id is required")
}
provider, err := h.service.GetProvider(c.Request().Context(), configID)
if err != nil {
return echo.NewHTTPError(http.StatusNotFound, "provider not found")
}
if provider.Provider != string(emailmailgun.ProviderName) {
return echo.NewHTTPError(http.StatusBadRequest, "provider is not mailgun")
}
mode, _ := provider.Config["inbound_mode"].(string)
if mode != emailmailgun.InboundModeWebhook {
return echo.NewHTTPError(http.StatusBadRequest, "provider is not in webhook mode")
}
adapter, err := h.service.Registry().Get(emailmailgun.ProviderName)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "mailgun adapter not available")
}
webhookReceiver, ok := adapter.(email.WebhookReceiver)
if !ok {
return echo.NewHTTPError(http.StatusInternalServerError, "mailgun adapter does not support webhooks")
}
var configMap map[string]any
configBytes, _ := json.Marshal(provider.Config)
_ = json.Unmarshal(configBytes, &configMap)
inbound, err := webhookReceiver.HandleWebhook(c.Request().Context(), configMap, c.Request())
if err != nil {
h.logger.Error("webhook handling failed", slog.Any("error", err))
return echo.NewHTTPError(http.StatusForbidden, err.Error())
}
if err := h.trigger.HandleInbound(c.Request().Context(), configID, *inbound); err != nil {
h.logger.Error("inbound processing failed", slog.Any("error", err))
return echo.NewHTTPError(http.StatusInternalServerError, "processing failed")
}
return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
}