mailserver

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// DefaultMaxMessageBytes is the default SMTP DATA limit (100 MiB).
	DefaultMaxMessageBytes int64 = 100 << 20

	// DefaultSMTPSPort is the registered implicit-TLS submission port. It is
	// privileged, so a deployment that cannot bind below 1024 has to move or
	// disable the listener. It has to stay equal to config.DefaultSMTPSPort,
	// which this package deliberately does not import: the mail server is
	// usable without the CLI configuration layer. A test in cmd/owlmail, which
	// already sees both, pins the equality.
	DefaultSMTPSPort = 465
)
View Source
const RuntimeReadinessMaxAge = 5 * time.Second

Variables

View Source
var ErrEmailNotFound = errors.New("email not found")

ErrEmailNotFound allows API adapters to distinguish a concurrent deletion from a storage failure without matching error text.

View Source
var ErrEmailSourceInUse = errors.New("email source is in use")

ErrEmailSourceInUse is returned when deletion would remove the source of an accepted relay that has not finished reading it yet.

View Source
var ErrInvalidCursor = errors.New("invalid or expired delivery cursor")

ErrInvalidCursor means the cursor is malformed, from another process, or ahead of this mailbox.

View Source
var ErrMailboxClosed = errors.New("mailbox closed")

ErrMailboxClosed means the mailbox stopped while a caller was waiting.

View Source
var ErrSMTPSBind = errors.New("SMTPS listener bind failed")

ErrSMTPSBind reports that the implicit-TLS listener could not take its address. The error states only what this package knows -- which listener failed, at which address, and why. The remedy is a CLI flag, and no other error in this package names one: cmd/owlmail wraps this error and adds the flags that move or disable the listener.

View Source
var ErrWaitCapacity = errors.New("delivery wait capacity reached")

ErrWaitCapacity means all bounded delivery wait slots are occupied.

Functions

func CheckMailDirectory added in v0.11.0

func CheckMailDirectory(directory string) error

CheckMailDirectory verifies create, write, sync, close and removal in an existing mail directory. It never creates the directory or opens the mailbox index.

func ResolveMailDirectory

func ResolveMailDirectory(mailDir string) string

ResolveMailDirectory returns the directory used by the server when callers leave the mail directory unset. Keeping this resolution in one place lets startup validate auxiliary storage paths against the effective directory.

func ResolveSMTPHost added in v0.11.0

func ResolveSMTPHost(host string) string

ResolveSMTPHost returns the effective listener identity, preserving wildcard binds.

func RuntimeReadinessPath added in v0.11.0

func RuntimeReadinessPath(directory, host string, port int) string

RuntimeReadinessPath keeps independent listeners in a shared directory separate.

func ValidateMailboxIndexPath

func ValidateMailboxIndexPath(mailDir, indexPath string) error

ValidateMailboxIndexPath rejects locations managed by OwlMail's storage and recovery machinery. Those paths are atomically replaced, moved, or removed without consulting the optional derived index, so sharing their namespace would eventually detach, corrupt, or delete the live SQLite database.

func ValidateRunID added in v0.11.0

func ValidateRunID(id string) error

ValidateRunID accepts a bounded, portable test-run identifier. Empty means ungrouped.

Types

type Attachment

type Attachment = types.Attachment

Attachment is an alias for types.Attachment

type AttachmentMigrationOptions

type AttachmentMigrationOptions struct {
	DryRun         bool
	DeleteLocal    bool
	Retries        int
	AttemptTimeout time.Duration
	RetryDelay     time.Duration
	Progress       func(AttachmentMigrationProgress)
	// contains filtered or unexported fields
}

AttachmentMigrationOptions configures the offline local-to-S3 migration. Retries is the number of attempts after the initial attempt.

type AttachmentMigrationProgress

type AttachmentMigrationProgress struct {
	EmailID  string
	Filename string
	Status   string
	Attempt  int
	Err      error
}

AttachmentMigrationProgress reports one observable migration transition.

type AttachmentMigrationSummary

type AttachmentMigrationSummary struct {
	EmailsScanned      int `json:"emailsScanned"`
	AttachmentsScanned int `json:"attachmentsScanned"`
	Planned            int `json:"planned"`
	Uploaded           int `json:"uploaded"`
	Verified           int `json:"verified"`
	AlreadyMigrated    int `json:"alreadyMigrated"`
	LocalFilesDeleted  int `json:"localFilesDeleted"`
	RetryAttempts      int `json:"retryAttempts"`
	Failed             int `json:"failed"`
}

AttachmentMigrationSummary reports the final migration counters.

func MigrateLocalAttachments

func MigrateLocalAttachments(ctx context.Context, mailDir string, store attachmentstore.Store, options AttachmentMigrationOptions) (AttachmentMigrationSummary, error)

MigrateLocalAttachments migrates decoded local attachments to the configured external store without starting SMTP or HTTP services. The caller must stop OwlMail before invoking it. Every source is preflighted before the first remote write, and migration state is committed atomically per attachment.

type AttachmentReader

type AttachmentReader struct {
	Body        io.ReadCloser
	ContentType string
	Size        int64
}

AttachmentReader describes an attachment opened for HTTP streaming.

type Backend

type Backend struct {
	// contains filtered or unexported fields
}

Backend implements smtp.Backend

func (*Backend) NewSession

func (b *Backend) NewSession(c *smtp.Conn) (smtp.Session, error)

NewSession creates a new SMTP session

type DeliveryFilter added in v0.11.0

type DeliveryFilter struct {
	Recipient string `json:"recipient,omitempty"`
	RunID     string `json:"run_id,omitempty"`
	Subject   string `json:"subject,omitempty"`
	Text      string `json:"text,omitempty"`
	// contains filtered or unexported fields
}

DeliveryFilter groups test messages without granting a separate security boundary. Recipient matches the complete SMTP envelope address, case-sensitively.

func (DeliveryFilter) Matches added in v0.11.0

func (f DeliveryFilter) Matches(e *Email) bool

Matches applies exact run/envelope selectors and case-insensitive content substrings.

func (DeliveryFilter) Validate added in v0.11.0

func (f DeliveryFilter) Validate() error

Validate checks filter bounds before waiting or querying.

type DeliveryResult added in v0.11.0

type DeliveryResult struct {
	Emails             []*Email `json:"emails"`
	Cursor             string   `json:"cursor"`
	TimedOut           bool     `json:"timed_out"`
	WaitedMilliseconds int64    `json:"waited_milliseconds"`
}

DeliveryResult contains detached committed messages, including a normal timeout outcome.

type Email

type Email = types.Email

Email is an alias for types.Email

type EmailPreview

type EmailPreview struct {
	ID            string    `json:"id"`
	Time          time.Time `json:"time"`
	Read          bool      `json:"read"`
	Subject       string    `json:"subject"`
	From          string    `json:"from"`
	To            []string  `json:"to"`
	Size          int64     `json:"size"`
	SizeHuman     string    `json:"sizeHuman"`
	HasAttachment bool      `json:"hasAttachment"`
	Preview       string    `json:"preview"`
}

EmailPreview is the detached, lightweight representation returned for a mailbox preview query.

func PreviewEmailSnapshot added in v0.11.0

func PreviewEmailSnapshot(email *Email) EmailPreview

PreviewEmailSnapshot projects an owned, detached email without looking it up again.

type EmailQuery

type EmailQuery struct {
	Text string
	// SearchAddresses includes sender and recipient names and addresses in the
	// free-text match. ExcludeHTML keeps compatibility queries aligned with
	// MailDev, whose summary search covers the plain-text body but not HTML.
	SearchAddresses bool
	ExcludeHTML     bool
	From            string
	To              string
	DateFrom        *time.Time
	DateTo          *time.Time
	Read            *bool
	SortBy          string
	SortOrder       string
	Offset          int
	Limit           int
	// MatchStoreEmail applies an additional filter while the mailbox read lock
	// is held. The callback must not retain or mutate the supplied store email.
	// It lets compatibility layers filter on their own DTO fields before full
	// messages are cloned for the selected page.
	MatchStoreEmail func(*Email) bool
}

EmailQuery describes a mailbox snapshot query. DateTo is the inclusive upper boundary used by the existing HTTP API, and Limit is applied after filtering and sorting.

type EmailSummary

type EmailSummary struct {
	ID              string
	Time            time.Time
	ReceivedAt      time.Time
	Read            bool
	Subject         string
	Size            int64
	SizeHuman       string
	From            []EmailSummaryAddress
	To              []EmailSummaryAddress
	CC              []EmailSummaryAddress
	AttachmentCount int
	Text            string
	EnvelopeFrom    string
	EnvelopeTo      []string
	SMTPEnvelope    bool
}

EmailSummary is a detached MailDev-capable summary projection. It contains no HTML, headers, envelope, or attachment metadata, so summary requests do not clone full messages before discarding those fields.

type EmailSummaryAddress

type EmailSummaryAddress struct {
	Name    string
	Address string
}

EmailSummaryAddress is a detached address used by lightweight summary projections that need both the display name and address.

type Envelope

type Envelope = types.Envelope

Envelope is an alias for types.Envelope

type Event

type Event struct {
	Type  string
	Email *types.Email
	ID    string
}

Event represents a server event

type IndexedEmail

type IndexedEmail struct {
	ID                      string
	MessageTime             time.Time
	ReceivedAt              time.Time
	Read                    bool
	SubjectSearch           string
	TextSearch              string
	HTMLSearch              string
	FromSearch              string
	VisibleRecipientsSearch string
	BCCAddressesSearch      string
	FirstFrom               string
	Size                    int64
	StorePosition           int
}

type IndexedEmailResult

type IndexedEmailResult struct {
	ID   string
	Read bool
}

type ListenerAddress added in v0.12.0

type ListenerAddress struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

ListenerAddress is an actual bound TCP listener address, with its OS-selected port.

type MailServer

type MailServer struct {
	// contains filtered or unexported fields
}

MailServer represents the SMTP mail server

func NewMailServer

func NewMailServer(port int, host, mailDir string) (*MailServer, error)

NewMailServer creates a new mail server instance

func NewMailServerWithConfig

func NewMailServerWithConfig(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig, authConfig *SMTPAuthConfig, tlsConfig *TLSConfig) (*MailServer, error)

NewMailServerWithConfig creates a new mail server instance with full configuration

func NewMailServerWithFullConfig

func NewMailServerWithFullConfig(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig, authConfig *SMTPAuthConfig, tlsConfig *TLSConfig, useUUIDForID bool) (*MailServer, error)

NewMailServerWithFullConfig creates a new mail server instance with full configuration including UUID option

func NewMailServerWithOptions

func NewMailServerWithOptions(port int, host, mailDir string, options ServerOptions) (*MailServer, error)

NewMailServerWithOptions creates a mail server with optional external attachment storage and a configurable SMTP message-size limit.

func NewMailServerWithOutgoing

func NewMailServerWithOutgoing(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig) (*MailServer, error)

NewMailServerWithOutgoing creates a new mail server instance with outgoing mail config

func (*MailServer) AcquireEmailSource

func (ms *MailServer) AcquireEmailSource(id string) (*Email, func(), error)

AcquireEmailSource atomically looks up an email and prevents all deletion paths, including retention cleanup, from removing its source until release is called. The returned release function is safe to call more than once.

func (*MailServer) AddCloser

func (ms *MailServer) AddCloser(closer io.Closer) error

AddCloser registers a component whose lifecycle is owned by the mail server. Its Close method must not synchronously call the owning mail server's Close.

func (*MailServer) BoundAddress added in v0.12.0

func (ms *MailServer) BoundAddress() (ListenerAddress, bool)

BoundAddress reports the actual SMTP address after all SMTP listeners bind. It is unavailable before binding and after the listener stops.

func (*MailServer) CleanupStorage

func (ms *MailServer) CleanupStorage() error

CleanupStorage removes oldest messages until every configured limit is met.

func (*MailServer) Close

func (ms *MailServer) Close() error

Close stops the SMTP server and waits for all owned resources to close. Concurrent callers share one shutdown, including its final error.

func (*MailServer) ConfigureStoragePolicy

func (ms *MailServer) ConfigureStoragePolicy(policy StoragePolicy) error

ConfigureStoragePolicy applies limits immediately and starts periodic cleanup.

func (*MailServer) DeleteAllEmail

func (ms *MailServer) DeleteAllEmail() error

DeleteAllEmail deletes all emails

func (*MailServer) DeleteEmail

func (ms *MailServer) DeleteEmail(id string) error

DeleteEmail deletes an email by ID

func (*MailServer) DeliveryCursor added in v0.11.0

func (ms *MailServer) DeliveryCursor() string

DeliveryCursor identifies the last committed message in this process. Restarts invalidate it.

func (*MailServer) EffectiveRelayRecipients

func (ms *MailServer) EffectiveRelayRecipients(email *Email) ([]string, error)

EffectiveRelayRecipients returns the outgoing rule-filtered recipient list used by a manual relay to the original SMTP envelope.

func (*MailServer) GetAllEmail

func (ms *MailServer) GetAllEmail() []*Email

GetAllEmail returns all emails

func (*MailServer) GetAttachmentHealth

func (ms *MailServer) GetAttachmentHealth() (attachmentstore.HealthStatus, bool)

GetAttachmentHealth returns the latest cached attachment-store readiness. A nil provider means external attachment storage is disabled.

func (*MailServer) GetAuthConfig

func (ms *MailServer) GetAuthConfig() *SMTPAuthConfig

GetAuthConfig returns the SMTP authentication configuration

func (*MailServer) GetAuthRequireTLS

func (ms *MailServer) GetAuthRequireTLS() bool

GetAuthRequireTLS reports whether SMTP AUTH is restricted to encrypted connections. Anonymous delivery in NO AUTH mode is unaffected.

func (*MailServer) GetEmail

func (ms *MailServer) GetEmail(id string) (*Email, error)

GetEmail retrieves an email by ID

func (*MailServer) GetEmailAttachment

func (ms *MailServer) GetEmailAttachment(id, filename string) (string, string, error)

GetEmailAttachment returns attachment file path

func (*MailServer) GetEmailHTML

func (ms *MailServer) GetEmailHTML(id string) (string, error)

GetEmailHTML returns the HTML content of an email

func (*MailServer) GetEmailPreview

func (ms *MailServer) GetEmailPreview(id string) (EmailPreview, bool)

GetEmailPreview returns one detached summary using the same snapshot and formatting boundary as QueryEmailPreviews.

func (*MailServer) GetEmailReceivedAt

func (ms *MailServer) GetEmailReceivedAt(id string) (time.Time, bool)

GetEmailReceivedAt returns OwlMail's capture timestamp for an email.

func (*MailServer) GetEmailStats

func (ms *MailServer) GetEmailStats() map[string]interface{}

GetEmailStats returns email statistics

func (*MailServer) GetEmailWithReceivedAt

func (ms *MailServer) GetEmailWithReceivedAt(id string) (*Email, time.Time, error)

GetEmailWithReceivedAt returns one consistent snapshot of both the message and its server-assigned capture timestamp.

func (*MailServer) GetHost

func (ms *MailServer) GetHost() string

GetHost returns the SMTP server host

func (*MailServer) GetMailDir

func (ms *MailServer) GetMailDir() string

GetMailDir returns the mail directory path

func (*MailServer) GetMailboxMetrics

func (ms *MailServer) GetMailboxMetrics() MailboxMetrics

GetMailboxMetrics returns current mailbox counts and retention counters without calculating on-disk usage.

func (*MailServer) GetMaxDataConcurrency

func (ms *MailServer) GetMaxDataConcurrency() int

GetMaxDataConcurrency returns the per-process SMTP DATA transaction limit. Zero means unlimited.

func (*MailServer) GetMaxMessageBytes

func (ms *MailServer) GetMaxMessageBytes() int64

GetMaxMessageBytes returns the configured inbound SMTP message-size limit.

func (*MailServer) GetMaxRecipients

func (ms *MailServer) GetMaxRecipients() int

GetMaxRecipients returns the maximum recipients accepted per message.

func (*MailServer) GetOutgoingConfig

func (ms *MailServer) GetOutgoingConfig() *outgoing.OutgoingConfig

GetOutgoingConfig returns the outgoing mail configuration

func (*MailServer) GetPort

func (ms *MailServer) GetPort() int

GetPort returns the SMTP server port

func (*MailServer) GetRawEmail

func (ms *MailServer) GetRawEmail(id string) (string, error)

GetRawEmail returns the raw email file path

func (*MailServer) GetRawEmailContent

func (ms *MailServer) GetRawEmailContent(id string) ([]byte, error)

GetRawEmailContent returns the raw email file content

func (*MailServer) GetRawEmailContentLimit

func (ms *MailServer) GetRawEmailContentLimit(id string, maxBytes int64) ([]byte, int64, bool, error)

GetRawEmailContentLimit returns at most maxBytes of the original message, together with its full on-disk size and whether the returned content was truncated. It preserves the same ID and path validation as GetRawEmail.

func (*MailServer) GetReadTimeout

func (ms *MailServer) GetReadTimeout() time.Duration

GetReadTimeout returns the SMTP read timeout shared by SMTP and SMTPS.

func (*MailServer) GetRelayJobHealth added in v0.11.0

func (ms *MailServer) GetRelayJobHealth() (attachmentstore.HealthStatus, bool)

GetRelayJobHealth omits the dependency when outgoing relay is not configured.

func (*MailServer) GetRuntimeReadiness added in v0.11.0

func (ms *MailServer) GetRuntimeReadiness() RuntimeReadiness

GetRuntimeReadiness returns credential-free cached state for either mode. It never touches disk or connects to a dependency.

func (*MailServer) GetSMTPSPort added in v0.10.0

func (ms *MailServer) GetSMTPSPort() int

GetSMTPSPort returns the port of the implicit-TLS listener, or zero when no implicit-TLS listener is configured. Callers cannot infer the port from the TLS settings alone: STARTTLS on the main port stays available when the implicit-TLS listener is switched off.

func (*MailServer) GetServiceReadiness added in v0.11.0

func (ms *MailServer) GetServiceReadiness() (bool, attachmentstore.HealthStatus)

GetServiceReadiness returns cached listener and local storage state. Health HTTP handlers never write to disk or dial SMTP just to answer a probe.

func (*MailServer) GetTLSConfig

func (ms *MailServer) GetTLSConfig() *TLSConfig

GetTLSConfig returns the TLS configuration

func (*MailServer) GetVisibleRawEmailContentLimit

func (ms *MailServer) GetVisibleRawEmailContentLimit(id string, maxBytes int64) ([]byte, int64, bool, error)

GetVisibleRawEmailContentLimit reads source only while the message belongs to the current mailbox snapshot. Holding the read lock through the file read prevents a concurrent read-only refresh from hiding the message after the visibility check but before the source is returned.

func (*MailServer) GetWriteTimeout

func (ms *MailServer) GetWriteTimeout() time.Duration

GetWriteTimeout returns the SMTP write timeout shared by SMTP and SMTPS.

func (*MailServer) InitializeRelayService added in v0.13.0

func (ms *MailServer) InitializeRelayService() error

InitializeRelayService loads the single durable relay owner and automatic handoffs before retention policies or SMTP listeners may expose this mailbox. It does not start delivery. Read-only observers never create relay state.

func (*MailServer) IsAutoRelayEnabled

func (ms *MailServer) IsAutoRelayEnabled() bool

IsAutoRelayEnabled reports whether the current immutable configuration enables automatic relay without exposing the relay implementation pointer.

func (*MailServer) Listen

func (ms *MailServer) Listen() error

Listen starts the SMTP server

func (*MailServer) ListenWithReady

func (ms *MailServer) ListenWithReady(ready func()) error

ListenWithReady binds every configured SMTP listener before calling ready and serving. Binding failures are returned without calling ready, so a listener that never came up cannot be reported as a successful start.

func (*MailServer) LoadMailsFromDirectory

func (ms *MailServer) LoadMailsFromDirectory() error

LoadMailsFromDirectory loads emails from the mail directory

func (*MailServer) On

func (ms *MailServer) On(event string, handler func(*types.Email))

On registers an event listener

func (*MailServer) OnSynchronous

func (ms *MailServer) OnSynchronous(event string, handler func(*types.Email) error) error

OnSynchronous registers a lightweight handoff listener that completes before emit returns. It is intended for durable queue writes, not network delivery or other long-running work. Only the "new" event has transactional rollback support, and only one handler is allowed because independent durable side effects cannot be rolled back safely when a later handler fails.

func (*MailServer) OnWithConcurrency

func (ms *MailServer) OnWithConcurrency(event string, maxConcurrency int, handler func(*types.Email)) error

OnWithConcurrency registers an event listener with an optional concurrency limit. A limit of zero preserves the original unlimited behavior. Limited listeners acquire a slot before their goroutine is created, providing real backpressure instead of accumulating goroutines that only wait on a lock.

func (*MailServer) OpenEmailAttachment

func (ms *MailServer) OpenEmailAttachment(id, filename string) (*AttachmentReader, error)

OpenEmailAttachment opens a local or S3-backed attachment for streaming.

func (*MailServer) QueryEmailPreviews

func (ms *MailServer) QueryEmailPreviews(query EmailQuery) ([]EmailPreview, int)

QueryEmailPreviews returns detached summaries for one page and the total number of matches before pagination. No full Email snapshot is created.

func (*MailServer) QueryEmailSummaries

func (ms *MailServer) QueryEmailSummaries(query EmailQuery) ([]EmailSummary, int)

QueryEmailSummaries returns lightweight detached summary projections for one page. Unlike QueryEmails, it never clones complete message bodies, headers, envelopes, or attachment records.

func (*MailServer) QueryEmails

func (ms *MailServer) QueryEmails(query EmailQuery) ([]*Email, int)

QueryEmails returns detached full-email snapshots for one page and the total number of matches before pagination. The store lock is released while filtering and sorting potentially large bodies, then reacquired only to deep-clone the selected page.

func (*MailServer) ReadAllEmail

func (ms *MailServer) ReadAllEmail() (int, error)

ReadAllEmail marks all emails as read, acknowledging only state that was durably persisted.

func (*MailServer) ReadEmail

func (ms *MailServer) ReadEmail(id string) error

ReadEmail marks a single email as read

func (*MailServer) RecordRelaySuccess added in v0.13.0

func (ms *MailServer) RecordRelaySuccess(id string, acceptedAt time.Time, recipients []string) error

RecordRelaySuccess records the last SMTP DATA acceptance independently from bounded job history. It must be called only after the downstream accepted the complete message, with the recipients used by that transaction. A persistence error never changes the fact that SMTP delivery succeeded: the in-memory receipt is retained and callers must repair metadata, not resend.

func (*MailServer) RefreshReadOnlyMailbox

func (ms *MailServer) RefreshReadOnlyMailbox() error

RefreshReadOnlyMailbox synchronizes the in-memory snapshot with committed EML files without recovery, metadata migration, quarantine, or any write to the mailbox. Newly observed messages emit the ordinary in-process new event.

func (*MailServer) RelayMail

func (ms *MailServer) RelayMail(email *Email, isAutoRelay bool, callback func(error)) error

RelayMail relays an email to the configured SMTP server

func (*MailServer) RelayMailAndWait

func (ms *MailServer) RelayMailAndWait(ctx context.Context, email *Email, relayTo string) error

RelayMailAndWait relays one message and waits for the outgoing worker's result. OwlMail's native API intentionally keeps its asynchronous enqueue semantics; the MailDev REST facade uses this method because MailDev only returns success after the relay attempt completes.

func (*MailServer) RelayMailConfirmed

func (ms *MailServer) RelayMailConfirmed(email *Email, recipients []string, callback func(error)) error

RelayMailConfirmed relays only when the current rule-filtered recipients match the list confirmed by the operator.

func (*MailServer) RelayMailTo

func (ms *MailServer) RelayMailTo(email *Email, relayTo string, callback func(error)) error

RelayMailTo relays an email to a specific address

func (*MailServer) RelayService added in v0.13.0

func (ms *MailServer) RelayService() *relay.Service

RelayService returns the shared durable task owner. It is nil for read-only observers or when automatic handoff recovery could not be loaded safely.

func (*MailServer) SaveEmailToStore

func (ms *MailServer) SaveEmailToStore(id string, isRead bool, envelope *Envelope, parsedEmail *Email) error

SaveEmailToStore saves a parsed email to the store (exported for testing)

func (*MailServer) SetOutgoingConfig

func (ms *MailServer) SetOutgoingConfig(config *outgoing.OutgoingConfig) (resultErr error)

SetOutgoingConfig sets the outgoing mail configuration

func (*MailServer) SetRelayJobReadinessProvider added in v0.11.0

func (ms *MailServer) SetRelayJobReadinessProvider(provider attachmentstore.ReadinessProvider)

SetRelayJobReadinessProvider registers the durable queue owner's cached health. The SMTP server never opens the queue or its records on behalf of a probe.

func (*MailServer) SetRetainAllHeaders

func (ms *MailServer) SetRetainAllHeaders(enabled bool)

SetRetainAllHeaders controls the complete header projection used only by optional compatibility APIs. Disabling it also releases any retained maps. Callers should configure it before the SMTP server starts receiving mail.

func (*MailServer) SetWebhookService added in v0.11.0

func (ms *MailServer) SetWebhookService(service *webhook.Service)

SetWebhookService registers diagnostics for the server-owned delivery service.

func (*MailServer) StartRelayRecovery added in v0.13.0

func (ms *MailServer) StartRelayRecovery() error

StartRelayRecovery begins persisted task recovery and automatic intent promotion. CLI callers invoke it only after all required listeners bind.

func (*MailServer) WaitDeliveries added in v0.11.0

func (ms *MailServer) WaitDeliveries(ctx context.Context, after string, filter DeliveryFilter, count int, timeout time.Duration) (DeliveryResult, error)

WaitDeliveries replays retained messages after a cursor and atomically subscribes to subsequent commits. It never polls, changes read state, or installs permanent listeners. Count is an at-least threshold (1..100), not an exactly-once delivery guarantee.

func (*MailServer) WebhookService added in v0.11.0

func (ms *MailServer) WebhookService() *webhook.Service

WebhookService returns the server-owned delivery service.

type MailboxIndex

type MailboxIndex interface {
	Rebuild([]IndexedEmail) error
	Upsert(IndexedEmail) error
	Delete(string) error
	Clear() error
	Query(EmailQuery) ([]IndexedEmailResult, int, error)
	OwnsPath(string) bool
	Backend() string
	Close() error
}

type MailboxMetrics

type MailboxMetrics struct {
	Total            int
	Read             int
	Unread           int
	ReceivedMessages uint64
	DeletedMessages  uint64
	Storage          StorageMetrics
}

MailboxMetrics is a disk-I/O-free snapshot for runtime monitoring.

type ReadOnlyRefreshPartialError

type ReadOnlyRefreshPartialError struct {
	// contains filtered or unexported fields
}

ReadOnlyRefreshPartialError reports files that could not be inspected while preserving every mailbox entry whose state could not be determined safely. The top-level mailbox directory was still readable.

func (*ReadOnlyRefreshPartialError) Error

func (err *ReadOnlyRefreshPartialError) Error() string

func (*ReadOnlyRefreshPartialError) Unwrap

func (err *ReadOnlyRefreshPartialError) Unwrap() error

type RuntimeReadiness added in v0.11.0

type RuntimeReadiness struct {
	Version    int                           `json:"version"`
	PID        int                           `json:"pid"`
	Host       string                        `json:"host"`
	Port       int                           `json:"port"`
	UpdatedAt  time.Time                     `json:"updated_at"`
	SMTP       bool                          `json:"smtp"`
	Storage    attachmentstore.HealthStatus  `json:"mail_storage"`
	Attachment *attachmentstore.HealthStatus `json:"attachment_store,omitempty"`
	Relay      *outgoing.RuntimeReadiness    `json:"relay,omitempty"`
	RelayJobs  *attachmentstore.HealthStatus `json:"relay_job_storage,omitempty"`
	Transport  *attachmentstore.HealthStatus `json:"outgoing_transport,omitempty"`
}

RuntimeReadiness is a credential-free snapshot published by the SMTP owner. It describes cached health, not final delivery or index integrity.

func (RuntimeReadiness) Validate added in v0.11.0

func (status RuntimeReadiness) Validate(host string, port int, now time.Time) error

func (RuntimeReadiness) ValidateService added in v0.11.0

func (status RuntimeReadiness) ValidateService(now time.Time) error

ValidateService applies the same dependency policy to HTTP readiness and snapshots. Snapshot ownership and publication freshness are checked by Validate.

type SMTPAuthConfig

type SMTPAuthConfig struct {
	Username string
	Password string
	Enabled  bool
}

SMTPAuthConfig represents required SMTP authentication configuration. A nil or disabled config selects NO AUTH mode.

type SQLiteMailboxIndex

type SQLiteMailboxIndex struct {
	// contains filtered or unexported fields
}

func NewSQLiteMailboxIndex

func NewSQLiteMailboxIndex(path string) (*SQLiteMailboxIndex, error)

func (*SQLiteMailboxIndex) Backend

func (index *SQLiteMailboxIndex) Backend() string

func (*SQLiteMailboxIndex) Clear

func (index *SQLiteMailboxIndex) Clear() error

func (*SQLiteMailboxIndex) Close

func (index *SQLiteMailboxIndex) Close() error

func (*SQLiteMailboxIndex) Delete

func (index *SQLiteMailboxIndex) Delete(id string) error

func (*SQLiteMailboxIndex) OwnsPath

func (index *SQLiteMailboxIndex) OwnsPath(path string) bool

func (*SQLiteMailboxIndex) Query

func (index *SQLiteMailboxIndex) Query(query EmailQuery) ([]IndexedEmailResult, int, error)

func (*SQLiteMailboxIndex) Rebuild

func (index *SQLiteMailboxIndex) Rebuild(records []IndexedEmail) error

func (*SQLiteMailboxIndex) Upsert

func (index *SQLiteMailboxIndex) Upsert(record IndexedEmail) error

type ServerOptions

type ServerOptions struct {
	// AllowEphemeralPort makes an explicit SMTP port zero bind an OS-selected
	// port. Legacy constructors and zero-valued options keep the default port.
	AllowEphemeralPort bool
	// DeferRelayRecovery keeps durable delivery paused until the application has
	// bound every required listener. Standalone SMTP callers leave it false.
	DeferRelayRecovery bool
	// ReadOnly requires an existing mail directory and prevents constructor
	// writes. It is used by observer processes such as the MCP stdio bridge.
	ReadOnly         bool
	RuntimeReadiness bool
	// RequireRelayJobReadiness keeps configured relay pending before the API
	// queue owner registers. Standalone SMTP library users can omit this.
	RequireRelayJobReadiness bool
	OutgoingConfig           *outgoing.OutgoingConfig
	AuthConfig               *SMTPAuthConfig
	AuthRequireTLS           bool
	TLSConfig                *TLSConfig
	UseUUIDForID             bool
	MaxMessageBytes          int64
	MaxDataConcurrency       int
	ReadTimeout              time.Duration
	WriteTimeout             time.Duration
	MaxRecipients            int
	// SMTPSPort is the port of the implicit-TLS (SMTPS) listener started
	// alongside the plain listener when TLSConfig is enabled. Zero starts no
	// implicit-TLS listener, which leaves STARTTLS on the main port as the
	// only encrypted path and avoids a second, possibly privileged, bind.
	SMTPSPort        int
	RetainAllHeaders bool
	AttachmentStore  attachmentstore.Store
	AttachmentHealth attachmentstore.ReadinessProvider
	MailboxIndex     MailboxIndex
}

ServerOptions contains optional runtime integrations and SMTP behavior. Zero MaxMessageBytes selects DefaultMaxMessageBytes. Zero MaxDataConcurrency leaves SMTP DATA concurrency unlimited. Zero protocol timeout and recipient fields select their established defaults. Zero SMTPSPort is the exception: it leaves the implicit-TLS listener unstarted instead of selecting a default, so a caller that wants the historical listener has to name DefaultSMTPSPort and accept its privileged bind.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents an SMTP session

func (*Session) Auth

func (s *Session) Auth(mechanism string) (sasl.Server, error)

Auth implements smtp.AuthSession for PLAIN and LOGIN authentication.

func (*Session) AuthMechanisms

func (s *Session) AuthMechanisms() []string

AuthMechanisms advertises the mechanisms supported in both modes. In NO AUTH mode credentials are accepted without validation so applications that insist on configuring SMTP credentials can still be tested without server setup.

func (*Session) Data

func (s *Session) Data(r io.Reader) error

Data handles the DATA command

func (*Session) Logout

func (s *Session) Logout() error

Logout closes the session

func (*Session) Mail

func (s *Session) Mail(from string, opts *smtp.MailOptions) error

Mail handles the MAIL FROM command

func (*Session) Rcpt

func (s *Session) Rcpt(to string, opts *smtp.RcptOptions) error

Rcpt handles the RCPT TO command

func (*Session) Reset

func (s *Session) Reset()

Reset resets the session

type StorageMetrics

type StorageMetrics struct {
	CleanupRuns      uint64    `json:"cleanupRuns"`
	DeletedMessages  uint64    `json:"deletedMessages"`
	ReclaimedBytes   uint64    `json:"reclaimedBytes"`
	LastCleanupAt    time.Time `json:"lastCleanupAt,omitempty"`
	LastCleanupError string    `json:"lastCleanupError,omitempty"`
}

StorageMetrics reports retention activity through the existing stats API.

type StoragePolicy

type StoragePolicy struct {
	MaxAge          time.Duration
	MaxMessages     int
	MaxDiskBytes    int64
	CleanupInterval time.Duration
}

StoragePolicy bounds the on-disk and in-memory mailbox.

type TLSConfig

type TLSConfig struct {
	CertFile string
	KeyFile  string
	Enabled  bool
}

TLSConfig represents TLS configuration for SMTP server

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL