Documentation
¶
Index ¶
- Constants
- Variables
- func CheckMailDirectory(directory string) error
- func ResolveMailDirectory(mailDir string) string
- func ResolveSMTPHost(host string) string
- func RuntimeReadinessPath(directory, host string, port int) string
- func ValidateMailboxIndexPath(mailDir, indexPath string) error
- func ValidateRunID(id string) error
- type Attachment
- type AttachmentMigrationOptions
- type AttachmentMigrationProgress
- type AttachmentMigrationSummary
- type AttachmentReader
- type Backend
- type DeliveryFilter
- type DeliveryResult
- type Email
- type EmailPreview
- type EmailQuery
- type EmailSummary
- type EmailSummaryAddress
- type Envelope
- type Event
- type IndexedEmail
- type IndexedEmailResult
- type ListenerAddress
- type MailServer
- func NewMailServer(port int, host, mailDir string) (*MailServer, error)
- func NewMailServerWithConfig(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig, ...) (*MailServer, error)
- func NewMailServerWithFullConfig(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig, ...) (*MailServer, error)
- func NewMailServerWithOptions(port int, host, mailDir string, options ServerOptions) (*MailServer, error)
- func NewMailServerWithOutgoing(port int, host, mailDir string, outgoingConfig *outgoing.OutgoingConfig) (*MailServer, error)
- func (ms *MailServer) AcquireEmailSource(id string) (*Email, func(), error)
- func (ms *MailServer) AddCloser(closer io.Closer) error
- func (ms *MailServer) BoundAddress() (ListenerAddress, bool)
- func (ms *MailServer) CleanupStorage() error
- func (ms *MailServer) Close() error
- func (ms *MailServer) ConfigureStoragePolicy(policy StoragePolicy) error
- func (ms *MailServer) DeleteAllEmail() error
- func (ms *MailServer) DeleteEmail(id string) error
- func (ms *MailServer) DeliveryCursor() string
- func (ms *MailServer) EffectiveRelayRecipients(email *Email) ([]string, error)
- func (ms *MailServer) GetAllEmail() []*Email
- func (ms *MailServer) GetAttachmentHealth() (attachmentstore.HealthStatus, bool)
- func (ms *MailServer) GetAuthConfig() *SMTPAuthConfig
- func (ms *MailServer) GetAuthRequireTLS() bool
- func (ms *MailServer) GetEmail(id string) (*Email, error)
- func (ms *MailServer) GetEmailAttachment(id, filename string) (string, string, error)
- func (ms *MailServer) GetEmailHTML(id string) (string, error)
- func (ms *MailServer) GetEmailPreview(id string) (EmailPreview, bool)
- func (ms *MailServer) GetEmailReceivedAt(id string) (time.Time, bool)
- func (ms *MailServer) GetEmailStats() map[string]interface{}
- func (ms *MailServer) GetEmailWithReceivedAt(id string) (*Email, time.Time, error)
- func (ms *MailServer) GetHost() string
- func (ms *MailServer) GetMailDir() string
- func (ms *MailServer) GetMailboxMetrics() MailboxMetrics
- func (ms *MailServer) GetMaxDataConcurrency() int
- func (ms *MailServer) GetMaxMessageBytes() int64
- func (ms *MailServer) GetMaxRecipients() int
- func (ms *MailServer) GetOutgoingConfig() *outgoing.OutgoingConfig
- func (ms *MailServer) GetPort() int
- func (ms *MailServer) GetRawEmail(id string) (string, error)
- func (ms *MailServer) GetRawEmailContent(id string) ([]byte, error)
- func (ms *MailServer) GetRawEmailContentLimit(id string, maxBytes int64) ([]byte, int64, bool, error)
- func (ms *MailServer) GetReadTimeout() time.Duration
- func (ms *MailServer) GetRelayJobHealth() (attachmentstore.HealthStatus, bool)
- func (ms *MailServer) GetRuntimeReadiness() RuntimeReadiness
- func (ms *MailServer) GetSMTPSPort() int
- func (ms *MailServer) GetServiceReadiness() (bool, attachmentstore.HealthStatus)
- func (ms *MailServer) GetTLSConfig() *TLSConfig
- func (ms *MailServer) GetVisibleRawEmailContentLimit(id string, maxBytes int64) ([]byte, int64, bool, error)
- func (ms *MailServer) GetWriteTimeout() time.Duration
- func (ms *MailServer) InitializeRelayService() error
- func (ms *MailServer) IsAutoRelayEnabled() bool
- func (ms *MailServer) Listen() error
- func (ms *MailServer) ListenWithReady(ready func()) error
- func (ms *MailServer) LoadMailsFromDirectory() error
- func (ms *MailServer) MailboxControl() *mailbox.Store
- func (ms *MailServer) MailboxView(id string) (*ScopedMailbox, error)
- func (ms *MailServer) MergeOwnership(ctx context.Context, sourceID, targetID string) error
- func (ms *MailServer) On(event string, handler func(*types.Email))
- func (ms *MailServer) OnSynchronous(event string, handler func(*types.Email) error) error
- func (ms *MailServer) OnWithConcurrency(event string, maxConcurrency int, handler func(*types.Email)) error
- func (ms *MailServer) OpenEmailAttachment(id, filename string) (*AttachmentReader, error)
- func (ms *MailServer) QueryEmailPreviews(query EmailQuery) ([]EmailPreview, int)
- func (ms *MailServer) QueryEmailSummaries(query EmailQuery) ([]EmailSummary, int)
- func (ms *MailServer) QueryEmails(query EmailQuery) ([]*Email, int)
- func (ms *MailServer) ReadAllEmail() (int, error)
- func (ms *MailServer) ReadEmail(id string) error
- func (ms *MailServer) RecordRelaySuccess(id string, acceptedAt time.Time, recipients []string) error
- func (ms *MailServer) RefreshReadOnlyMailbox() error
- func (ms *MailServer) RelayMail(email *Email, isAutoRelay bool, callback func(error)) error
- func (ms *MailServer) RelayMailAndWait(ctx context.Context, email *Email, relayTo string) error
- func (ms *MailServer) RelayMailConfirmed(email *Email, recipients []string, callback func(error)) error
- func (ms *MailServer) RelayMailTo(email *Email, relayTo string, callback func(error)) error
- func (ms *MailServer) RelayService() *relay.Service
- func (ms *MailServer) RequiresOwnership() bool
- func (ms *MailServer) RetainPending(ctx context.Context, item mailbox.PendingRetention) (mailbox.PendingRetentionResult, error)
- func (ms *MailServer) SaveEmailToStore(id string, isRead bool, envelope *Envelope, parsedEmail *Email) error
- func (ms *MailServer) SetOutgoingConfig(config *outgoing.OutgoingConfig) (resultErr error)
- func (ms *MailServer) SetRelayJobReadinessProvider(provider attachmentstore.ReadinessProvider)
- func (ms *MailServer) SetRetainAllHeaders(enabled bool)
- func (ms *MailServer) SetWebhookService(service *webhook.Service)
- func (ms *MailServer) StartRelayRecovery() error
- func (ms *MailServer) WaitDeliveries(ctx context.Context, after string, filter DeliveryFilter, count int, ...) (DeliveryResult, error)
- func (ms *MailServer) WebhookService() *webhook.Service
- type MailboxIndex
- type MailboxMetrics
- type MailboxMigrationOptions
- type MailboxMigrationResult
- type ReadOnlyRefreshPartialError
- type RoutedIngressOptions
- type RuntimeReadiness
- type SMTPAuthConfig
- type SQLiteMailboxIndex
- func (index *SQLiteMailboxIndex) Backend() string
- func (index *SQLiteMailboxIndex) Clear() error
- func (index *SQLiteMailboxIndex) Close() error
- func (index *SQLiteMailboxIndex) Delete(id string) error
- func (index *SQLiteMailboxIndex) OwnsPath(path string) bool
- func (index *SQLiteMailboxIndex) Query(query EmailQuery) ([]IndexedEmailResult, int, error)
- func (index *SQLiteMailboxIndex) Rebuild(records []IndexedEmail) error
- func (index *SQLiteMailboxIndex) Upsert(record IndexedEmail) error
- type ScopedMailbox
- func (v *ScopedMailbox) Cursor() (string, error)
- func (v *ScopedMailbox) Delete(ids []string) (int, error)
- func (v *ScopedMailbox) Get(id string) (*Email, error)
- func (v *ScopedMailbox) IDs(q EmailQuery) []string
- func (v *ScopedMailbox) List(q EmailQuery) ([]*Email, int)
- func (v *ScopedMailbox) OpenAttachment(id, name string) (*AttachmentReader, error)
- func (v *ScopedMailbox) OpenRaw(id string) (io.ReadCloser, int64, error)
- func (v *ScopedMailbox) Previews(q EmailQuery) ([]EmailPreview, int)
- func (v *ScopedMailbox) Read(ids []string) (int, error)
- func (v *ScopedMailbox) Stats() map[string]interface{}
- func (v *ScopedMailbox) ValidateIDs(ids []string) error
- func (v *ScopedMailbox) Wait(ctx context.Context, after string, filter DeliveryFilter, count int, ...) (DeliveryResult, error)
- type ServerOptions
- type Session
- func (s *Session) Auth(mechanism string) (sasl.Server, error)
- func (s *Session) AuthMechanisms() []string
- func (s *Session) Data(r io.Reader) error
- func (s *Session) Logout() error
- func (s *Session) Mail(from string, opts *smtp.MailOptions) error
- func (s *Session) Rcpt(to string, opts *smtp.RcptOptions) error
- func (s *Session) Reset()
- type StorageMetrics
- type StoragePolicy
- type TLSConfig
Constants ¶
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 )
const RuntimeReadinessMaxAge = 5 * time.Second
Variables ¶
var ErrEmailNotFound = errors.New("email not found")
ErrEmailNotFound allows API adapters to distinguish a concurrent deletion from a storage failure without matching error text.
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.
var ErrInvalidCursor = errors.New("invalid or expired delivery cursor")
ErrInvalidCursor means the cursor is malformed, from another process, or ahead of this mailbox.
var ErrMailboxClosed = errors.New("mailbox closed")
ErrMailboxClosed means the mailbox stopped while a caller was waiting.
var ErrMailboxQuota = mailbox.ErrQuotaExceeded
ErrMailboxQuota is a temporary submission/merge refusal. No journal or metadata is changed when a quota preflight fails.
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.
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
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 ¶
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
ResolveSMTPHost returns the effective listener identity, preserving wildcard binds.
func RuntimeReadinessPath ¶ added in v0.11.0
RuntimeReadinessPath keeps independent listeners in a shared directory separate.
func ValidateMailboxIndexPath ¶
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
ValidateRunID accepts a bounded, portable test-run identifier. Empty means ungrouped.
Types ¶
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
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 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 ¶
EmailSummaryAddress is a detached address used by lightweight summary projections that need both the display name and address.
type IndexedEmail ¶
type IndexedEmailResult ¶
type ListenerAddress ¶ added in v0.12.0
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 ¶
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) 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) MailboxControl ¶ added in v0.14.0
func (ms *MailServer) MailboxControl() *mailbox.Store
MailboxControl returns the shared authority for routed ingress and HTTP identity binding. Its lifetime belongs to the application, never to individual requests.
func (*MailServer) MailboxView ¶ added in v0.14.0
func (ms *MailServer) MailboxView(id string) (*ScopedMailbox, error)
func (*MailServer) MergeOwnership ¶ added in v0.14.0
func (ms *MailServer) MergeOwnership(ctx context.Context, sourceID, targetID string) error
MergeOwnership idempotently moves a frozen pending mailbox's committed messages to a personal mailbox. The control Store must hold its mutation lock and validate the merge journal before calling this method. This method does not bind identities, publish new-email events, create Relay/Webhook work, or replay historical delivery. Control commit happens only after this succeeds. Lock order: control Store -> storageTransactionMutex -> storeMutex.
func (*MailServer) On ¶
func (ms *MailServer) On(event string, handler func(*types.Email))
On registers an event listener
func (*MailServer) OnSynchronous ¶
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 ¶
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) RequiresOwnership ¶ added in v0.14.0
func (ms *MailServer) RequiresOwnership() bool
RequiresOwnership identifies isolated storage without exposing another user's ID.
func (*MailServer) RetainPending ¶ added in v0.14.0
func (ms *MailServer) RetainPending(ctx context.Context, item mailbox.PendingRetention) (mailbox.PendingRetentionResult, error)
RetainPending applies a control-store-authorized pending cleanup. The caller must hold Store.mu via RunPendingRetention/CleanupPending. It never emits deletion events, creates outbound work, or removes personal mailbox data. The control journal is authoritative until this idempotent callback succeeds.
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 MailboxMigrationOptions ¶ added in v0.14.0
type MailboxMigrationOptions struct {
Source string
Destination string
Direction string
Namespace string
Subject string
MailboxID string
ControlDatabase string
Offline bool
// contains filtered or unexported fields
}
MailboxMigrationOptions describes an offline copy, never an in-place upgrade. Offline is the operator's assertion that every writer has been stopped. The migration additionally compares source inventories before publishing output.
type MailboxMigrationResult ¶ added in v0.14.0
type MailboxMigrationResult struct {
Version int `json:"version"`
Direction string `json:"direction"`
Namespace string `json:"namespace,omitempty"`
Subject string `json:"subject,omitempty"`
MailboxID string `json:"mailboxId"`
SourceFingerprint string `json:"sourceFingerprint"`
SourceControlHash string `json:"sourceControlHash,omitempty"`
Emails int `json:"emails"`
Attachments int `json:"attachments"`
Files []migrationFile `json:"files"`
AlreadyComplete bool `json:"-"`
}
MailboxMigrationResult is also the private, checksummed bundle receipt.
func MigrateMailbox ¶ added in v0.14.0
func MigrateMailbox(ctx context.Context, options MailboxMigrationOptions) (MailboxMigrationResult, error)
MigrateMailbox creates destination/{mail,control.sqlite,source-archive} for imports, or destination/{mail,source-archive} for a single-person export. Publication is one rename on the destination filesystem. Rollback means discarding this new bundle: source content is never modified.
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 RoutedIngressOptions ¶ added in v0.14.0
type RoutedIngressOptions struct {
Accounts *mailbox.Accounts
Control *mailbox.Store
MaxPending int
MaxCreatesPerMinute int
MaxAuthPerMinute int
MaxMessages int
MaxDiskBytes int64
MaxTotalMessages int
MaxTotalDiskBytes int64
}
RoutedIngressOptions configures authenticated system SMTP, not user login. The caller retains ownership of Control and must close it after MailServer.
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) 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 ¶
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 ScopedMailbox ¶ added in v0.14.0
type ScopedMailbox struct {
// contains filtered or unexported fields
}
ScopedMailbox exposes only one mailbox. Callers must obtain its ID from the authenticated control store, never from a URL or a client-owned header.
func (*ScopedMailbox) Cursor ¶ added in v0.14.0
func (v *ScopedMailbox) Cursor() (string, error)
func (*ScopedMailbox) Delete ¶ added in v0.14.0
func (v *ScopedMailbox) Delete(ids []string) (int, error)
func (*ScopedMailbox) IDs ¶ added in v0.14.0
func (v *ScopedMailbox) IDs(q EmailQuery) []string
func (*ScopedMailbox) List ¶ added in v0.14.0
func (v *ScopedMailbox) List(q EmailQuery) ([]*Email, int)
func (*ScopedMailbox) OpenAttachment ¶ added in v0.14.0
func (v *ScopedMailbox) OpenAttachment(id, name string) (*AttachmentReader, error)
func (*ScopedMailbox) OpenRaw ¶ added in v0.14.0
func (v *ScopedMailbox) OpenRaw(id string) (io.ReadCloser, int64, error)
func (*ScopedMailbox) Previews ¶ added in v0.14.0
func (v *ScopedMailbox) Previews(q EmailQuery) ([]EmailPreview, int)
func (*ScopedMailbox) Read ¶ added in v0.14.0
func (v *ScopedMailbox) Read(ids []string) (int, error)
func (*ScopedMailbox) Stats ¶ added in v0.14.0
func (v *ScopedMailbox) Stats() map[string]interface{}
func (*ScopedMailbox) ValidateIDs ¶ added in v0.14.0
func (v *ScopedMailbox) ValidateIDs(ids []string) error
ValidateIDs checks the complete batch before any mutation. It deliberately returns the same missing error for foreign and absent messages.
func (*ScopedMailbox) Wait ¶ added in v0.14.0
func (v *ScopedMailbox) Wait(ctx context.Context, after string, filter DeliveryFilter, count int, timeout time.Duration) (DeliveryResult, error)
type ServerOptions ¶
type ServerOptions struct {
// RequireOwnership selects isolated storage; standalone directories remain unchanged.
RequireOwnership bool
RoutedIngress *RoutedIngressOptions
// 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) AuthMechanisms ¶
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) Mail ¶
func (s *Session) Mail(from string, opts *smtp.MailOptions) error
Mail handles the MAIL FROM command
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.
Source Files
¶
- address.go
- attachment_migration.go
- attachment_storage.go
- auth.go
- automatic_relay.go
- config.go
- data_limiter.go
- delivery_wait.go
- events.go
- lifecycle.go
- mailbox_index.go
- migrate_mailbox.go
- migrate_snapshot.go
- multipart.go
- outgoing_readiness.go
- ownership.go
- ownership_merge.go
- pending_retention.go
- query.go
- read_only.go
- readiness.go
- relay.go
- relay_job_readiness.go
- relay_receipt.go
- relay_service.go
- routed_ingress.go
- runtime_readiness.go
- scoped.go
- session.go
- snapshot.go
- sqlite_index.go
- storage_deletion.go
- storage_governance.go
- storage_transaction.go
- store.go
- types.go
- utils.go
- webhook_service.go