email

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2025 License: BSD-3-Clause Imports: 27 Imported by: 0

Documentation

Overview

Package email provides high-performance email sending capabilities.

Package email provides helpers for formatting and delivering mail via SMTP.

SendWithClient sanitizing and deduplicates recipients case-insensitively across the To, CC, and BCC lists in that order. The primary recipient is always addressed first, and only one RCPT command is issued per unique address. CC headers include only deduplicated CC recipients while BCC addresses are added to the envelope but never leaked via headers.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrPoolClosed      = errors.New("connection pool is closed")
	ErrPoolExhausted   = errors.New("connection pool exhausted")
	ErrConnectionStale = errors.New("connection is stale")
)
View Source
var (
	ErrAttachmentTooLarge        = errors.New("attachment exceeds maximum allowed size")
	ErrUnsupportedAttachmentType = errors.New("unsupported attachment type")
)
View Source
var (
	ErrCircuitBreakerOpen = errors.New("circuit breaker is open")
)

Functions

func ConnectSMTP

func ConnectSMTP(cfg config.SMTPConfig) (*smtp.Client, error)

ConnectSMTP establishes a persistent, authenticated SMTP client with TLS.

func SendWithClient

func SendWithClient(client *smtp.Client, cfg config.SMTPConfig, task Task) (err error)

SendWithClient formats and delivers an email using an active SMTP client. Recipients from the To, CC, and BCC fields are trimmed, deduplicated in that order (case-insensitively), and issued RCPT commands exactly once with the primary recipient always first. The CC header is rendered from the unique CC list, while BCC addresses are kept solely on the SMTP envelope. It uses cfg.SMTP.From as both the envelope sender and header From address.

func SetRetryLimit

func SetRetryLimit(limit int)

SetRetryLimit sets the max retry attempts per failed email, with exponential backoff.

func StartDispatcher

func StartDispatcher(tasks []Task, cfg config.SMTPConfig, concurrency int, batchSize int)

StartDispatcher spawns workers and processes email tasks with retries and batch-mode dispatch.

Types

type AttachmentProcessor added in v1.0.0

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

AttachmentProcessor handles efficient processing of email attachments

func NewAttachmentProcessor added in v1.0.0

func NewAttachmentProcessor(maxSize int64) *AttachmentProcessor

NewAttachmentProcessor creates a new attachment processor

func (*AttachmentProcessor) ProcessAttachment added in v1.0.0

func (p *AttachmentProcessor) ProcessAttachment(path string) (io.Reader, string, error)

ProcessAttachment handles a single attachment efficiently

type BatchConfig added in v1.0.0

type BatchConfig struct {
	MinBatchSize     int
	MaxBatchSize     int
	TargetLatency    time.Duration
	AdaptationPeriod time.Duration
}

BatchConfig provides configuration for batch processing

type BatchMetrics added in v1.0.0

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

BatchMetrics tracks performance metrics for batch processing

type BatchProcessor added in v1.0.0

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

BatchProcessor handles adaptive batch processing of emails

func NewBatchProcessor added in v1.0.0

func NewBatchProcessor(pool *SMTPPool, config BatchConfig) *BatchProcessor

NewBatchProcessor creates a new batch processor with given configuration

func (*BatchProcessor) Add added in v1.0.0

func (p *BatchProcessor) Add(task Task)

Add adds a task to the current batch

func (*BatchProcessor) GetMetrics added in v1.0.0

func (p *BatchProcessor) GetMetrics() BatchStats

GetMetrics returns current batch processing metrics

func (*BatchProcessor) Start added in v1.0.0

func (p *BatchProcessor) Start(ctx context.Context)

Start starts the batch processor

type BatchStats added in v1.0.0

type BatchStats struct {
	AvgProcessingTime  time.Duration
	Successes          int64
	Failures           int64
	OptimalBatchSize   int
	MinSuccessfulBatch int
	MaxSuccessfulBatch int
	CurrentBatchSize   int
}

BatchStats provides metrics about batch processing

type CircuitBreaker added in v1.0.0

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

CircuitBreaker implements circuit breaker pattern for email sending

func NewCircuitBreaker added in v1.0.0

func NewCircuitBreaker(maxFailures int64, timeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Call added in v1.0.0

func (cb *CircuitBreaker) Call(ctx context.Context, fn func() error) error

Call executes a function with circuit breaker protection

func (*CircuitBreaker) GetState added in v1.0.0

func (cb *CircuitBreaker) GetState() CircuitBreakerStats

GetState returns current circuit breaker state and metrics

type CircuitBreakerState added in v1.0.0

type CircuitBreakerState int

CircuitBreakerState represents the current state of a circuit breaker

const (
	Closed CircuitBreakerState = iota
	Open
	HalfOpen
)

type CircuitBreakerStats added in v1.0.0

type CircuitBreakerStats struct {
	State        CircuitBreakerState
	Failures     int64
	Successes    int64
	LastFailTime time.Time
	NextAttempt  time.Time
	ErrorCounts  map[ErrorType]int64
	RecentErrors []string
}

CircuitBreakerStats provides metrics about circuit breaker state

type ErrorClassifier added in v1.0.0

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

ErrorClassifier classifies errors for circuit breaker decisions

func NewErrorClassifier added in v1.0.0

func NewErrorClassifier() *ErrorClassifier

NewErrorClassifier creates a new error classifier

func (*ErrorClassifier) ClassifyError added in v1.0.0

func (c *ErrorClassifier) ClassifyError(err error) ErrorType

ClassifyError determines the type of error

type ErrorType added in v1.0.0

type ErrorType int

ErrorClassifier defines different types of errors

const (
	UnknownError ErrorType = iota
	NetworkError
	AuthError
	QuotaError
	TemporaryError
	PermanentError
)

type Pipeline added in v1.0.0

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

Pipeline represents a sequence of SMTP commands to be executed

func NewPipeline added in v1.0.0

func NewPipeline(size int) *Pipeline

NewPipeline creates a new command pipeline

func (*Pipeline) QueueCommand added in v1.0.0

func (p *Pipeline) QueueCommand(format string, args ...interface{})

QueueCommand adds a command to the pipeline

type PoolConfig added in v1.0.0

type PoolConfig struct {
	// Initial number of connections in pool
	InitialSize int
	// Maximum number of connections pool can hold
	MaxSize int
	// Maximum time a connection can be idle before being closed
	MaxIdleTime time.Duration
	// Maximum time to wait for a connection from pool
	MaxWaitTime time.Duration
	// How often to check connection health
	HealthCheckInterval time.Duration
}

type ResilienceManager added in v1.0.0

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

ResilienceManager combines circuit breaker and retry logic

func NewResilienceManager added in v1.0.0

func NewResilienceManager(maxFailures int64, timeout time.Duration, retryPolicy *RetryPolicy) *ResilienceManager

NewResilienceManager creates a new resilience manager

func (*ResilienceManager) Execute added in v1.0.0

func (rm *ResilienceManager) Execute(ctx context.Context, fn func() error) error

Execute runs a function with both circuit breaker and retry protection

func (*ResilienceManager) GetStats added in v1.0.0

func (rm *ResilienceManager) GetStats() ResilienceStats

GetStats returns current resilience manager statistics

type ResilienceStats added in v1.0.0

type ResilienceStats struct {
	CircuitBreaker CircuitBreakerStats
}

ResilienceStats provides overall resilience statistics

type RetryPolicy added in v1.0.0

type RetryPolicy struct {
	MaxRetries      int
	BaseDelay       time.Duration
	MaxDelay        time.Duration
	BackoffFactor   float64
	RetryableErrors map[ErrorType]bool
}

RetryPolicy defines retry behavior

func DefaultRetryPolicy added in v1.0.0

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy returns a sensible default retry policy

func (*RetryPolicy) Retry added in v1.0.0

func (rp *RetryPolicy) Retry(ctx context.Context, classifier *ErrorClassifier, fn func() error) error

Retry executes a function with retry logic

type SMTPPipeline added in v1.0.0

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

SMTPPipeline provides optimized SMTP command pipelining

func NewSMTPPipeline added in v1.0.0

func NewSMTPPipeline(conn net.Conn, maxPipeline int, flushInterval time.Duration) *SMTPPipeline

NewSMTPPipeline creates a new SMTP pipeline with the given connection

func (*SMTPPipeline) Auth added in v1.0.0

func (s *SMTPPipeline) Auth(auth smtp.Auth) error

Auth performs SMTP authentication

func (*SMTPPipeline) Close added in v1.0.0

func (s *SMTPPipeline) Close() error

Close closes the connection

func (*SMTPPipeline) ExecutePipeline added in v1.0.0

func (s *SMTPPipeline) ExecutePipeline(p *Pipeline) error

ExecutePipeline executes a batch of SMTP commands with pipelining

func (*SMTPPipeline) StartTLS added in v1.0.0

func (s *SMTPPipeline) StartTLS(config *tls.Config) error

StartTLS initiates a TLS session

type SMTPPool added in v1.0.0

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

SMTPPool manages a pool of SMTP connections with health checking and circuit breaking

func NewSMTPPool added in v1.0.0

func NewSMTPPool(smtpCfg config.SMTPConfig, poolCfg PoolConfig) (*SMTPPool, error)

NewSMTPPool creates a new connection pool with the given configuration

func (*SMTPPool) Close added in v1.0.0

func (p *SMTPPool) Close() error

Close closes the connection pool and all its connections

func (*SMTPPool) Get added in v1.0.0

func (p *SMTPPool) Get(ctx context.Context) (*smtp.Client, error)

Get gets a connection from the pool, creating a new one if needed

func (*SMTPPool) Put added in v1.0.0

func (p *SMTPPool) Put(client *smtp.Client) error

Put returns a connection to the pool

type Task

type Task struct {
	Recipient   parser.Recipient
	Subject     string
	Body        string
	Retries     int
	Attachments []string
	CC          []string
	BCC         []string
}

Task represents an email send job with recipient data.

type TemplateCache added in v1.0.0

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

TemplateCache provides thread-safe caching of parsed email templates

func NewTemplateCache added in v1.0.0

func NewTemplateCache(maxAge time.Duration, maxSize int) *TemplateCache

NewTemplateCache creates a new template cache with given configuration

func (*TemplateCache) Clear added in v1.0.0

func (c *TemplateCache) Clear()

Clear removes all templates from cache

func (*TemplateCache) Get added in v1.0.0

func (c *TemplateCache) Get(path string) (*template.Template, error)

Get retrieves a template from cache or parses it if not found

Jump to

Keyboard shortcuts

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