Files
Memoh/internal/email/outbox.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

148 lines
3.8 KiB
Go

package email
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"github.com/memohai/memoh/internal/db"
"github.com/memohai/memoh/internal/db/sqlc"
)
// OutboxService manages the email outbox audit log.
type OutboxService struct {
queries *sqlc.Queries
logger *slog.Logger
}
func NewOutboxService(log *slog.Logger, queries *sqlc.Queries) *OutboxService {
return &OutboxService{
queries: queries,
logger: log.With(slog.String("service", "email_outbox")),
}
}
// Create records a pending outbound email.
func (s *OutboxService) Create(ctx context.Context, providerID, botID string, msg OutboundEmail, fromAddr string) (string, error) {
pgProviderID, err := db.ParseUUID(providerID)
if err != nil {
return "", fmt.Errorf("invalid provider_id: %w", err)
}
pgBotID, err := db.ParseUUID(botID)
if err != nil {
return "", fmt.Errorf("invalid bot_id: %w", err)
}
toJSON, _ := json.Marshal(msg.To)
bodyText, bodyHTML := msg.Body, ""
if msg.HTML {
bodyHTML = msg.Body
bodyText = ""
}
row, err := s.queries.CreateEmailOutbox(ctx, sqlc.CreateEmailOutboxParams{
ProviderID: pgProviderID,
BotID: pgBotID,
FromAddress: fromAddr,
ToAddresses: toJSON,
Subject: msg.Subject,
BodyText: bodyText,
BodyHtml: bodyHTML,
Attachments: []byte("[]"),
Status: "pending",
})
if err != nil {
return "", fmt.Errorf("create outbox: %w", err)
}
return row.ID.String(), nil
}
// MarkSent updates the outbox record with a successful send.
func (s *OutboxService) MarkSent(ctx context.Context, id, messageID string) error {
pgID, err := db.ParseUUID(id)
if err != nil {
return err
}
return s.queries.UpdateEmailOutboxSent(ctx, sqlc.UpdateEmailOutboxSentParams{
ID: pgID,
MessageID: messageID,
})
}
// MarkFailed updates the outbox record with an error.
func (s *OutboxService) MarkFailed(ctx context.Context, id, errMsg string) error {
pgID, err := db.ParseUUID(id)
if err != nil {
return err
}
return s.queries.UpdateEmailOutboxFailed(ctx, sqlc.UpdateEmailOutboxFailedParams{
ID: pgID,
Error: errMsg,
})
}
func (s *OutboxService) Get(ctx context.Context, id string) (OutboxItemResponse, error) {
pgID, err := db.ParseUUID(id)
if err != nil {
return OutboxItemResponse{}, err
}
row, err := s.queries.GetEmailOutboxByID(ctx, pgID)
if err != nil {
return OutboxItemResponse{}, fmt.Errorf("get outbox: %w", err)
}
return s.toOutboxResponse(row), nil
}
func (s *OutboxService) ListByBot(ctx context.Context, botID string, limit, offset int32) ([]OutboxItemResponse, int64, error) {
pgBotID, err := db.ParseUUID(botID)
if err != nil {
return nil, 0, err
}
rows, err := s.queries.ListEmailOutboxByBot(ctx, sqlc.ListEmailOutboxByBotParams{
BotID: pgBotID,
Lim: limit,
Off: offset,
})
if err != nil {
return nil, 0, fmt.Errorf("list outbox: %w", err)
}
count, err := s.queries.CountEmailOutboxByBot(ctx, pgBotID)
if err != nil {
return nil, 0, fmt.Errorf("count outbox: %w", err)
}
items := make([]OutboxItemResponse, 0, len(rows))
for _, row := range rows {
items = append(items, s.toOutboxResponse(row))
}
return items, count, nil
}
func (s *OutboxService) toOutboxResponse(row sqlc.EmailOutbox) OutboxItemResponse {
var to []string
_ = json.Unmarshal(row.ToAddresses, &to)
var attachments []any
_ = json.Unmarshal(row.Attachments, &attachments)
var sentAt interface{ IsZero() bool }
resp := OutboxItemResponse{
ID: row.ID.String(),
ProviderID: row.ProviderID.String(),
BotID: row.BotID.String(),
MessageID: row.MessageID,
From: row.FromAddress,
To: to,
Subject: row.Subject,
BodyText: row.BodyText,
BodyHTML: row.BodyHtml,
Attachments: attachments,
Status: row.Status,
Error: row.Error,
CreatedAt: row.CreatedAt.Time,
}
_ = sentAt
if row.SentAt.Valid {
resp.SentAt = row.SentAt.Time
}
return resp
}