## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# email/memory

> Package memory is an email sender that sends nothing: it keeps each message in an outbox in the process's memory, for tests and local development, as a gas.EmailProvider.

The Markdown of https://gasmod.dev/reference/email/memory/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
import "github.com/gasmod/gas/email/memory"
```

Package memory is an email sender that sends nothing: it keeps each
message in an outbox in the process's memory, for tests and local
development, as a gas.EmailProvider.

[Service](#Service) implements gas.Service, gas.EmailProvider and
gas.ReadyReporter, and keeps the contract of the email package. It has
the same rules and the same template rendering as gas/email/ses, so a
message the memory sender accepts is one the SES sender would send.

## Usage

In an app, the container builds the sender from [New](#New) and calls its
Init. By hand, with a configuration given in code:

```go
cfg := memory.DefaultConfig()
cfg.Email.FromEmail = "Shop <shop@example.com>"

m, err := memory.New(memory.WithConfig(cfg))(templates, nil, logger)
if err != nil {
	return err
}
if err := m.Init(ctx); err != nil {
	return err
}
defer m.Close(ctx)

err = m.Send(ctx, &gas.Email{
	To:       []string{"alice@example.com"},
	Subject:  "Your order",
	TextBody: "It ships today.",
})
sent := m.Messages()
```

After this sent holds one message, from `Shop <shop@example.com>` to
`alice@example.com`.

## Configuration

The settings live in the `email` section, in [Settings](#Settings):

- `email.fromemail`: the sender of a message whose From is empty, one
email address as the email package reads one, which Init
normalizes. Default: none, so every message needs a From.
- `email.maxmessages`: the most messages the outbox holds, at least
1. Default: [DefaultMaxMessages](#DefaultMaxMessages) (10000).
- `email.maxbytes`: the most bytes the messages of the outbox hold,
each counted as email.MessageSize estimates it, at least
[MinMaxBytes](#MinMaxBytes) (1 MiB). Default: [DefaultMaxBytes](#DefaultMaxBytes) (256 MiB).

[Service.Init](#Service.Init) resolves the configuration each time it runs, from one
of two sources:

- Without [WithConfig](#WithConfig), it binds [DefaultConfig](#DefaultConfig) from the
gas.ConfigProvider, which checks the `validate` tags. A nil
ConfigProvider is the error email.ErrNoConfigProvider.
- With WithConfig, it takes a copy of the given Config, never
changing the caller's struct, and checks the same tags.

Then `fromemail`, when set, must be one email address. A failure wraps
email.ErrInvalidConfig and names the setting, never its value.

[Service.Config](#Service.Config) returns a copy of the configuration the last
successful Init resolved, defaults included, or the zero Config before
one. A failed Init and Close leave it as it was. Its `fromemail` is the
normalized address.

## Outbox

A send that keeps every rule stores a copy of the normalized message
CheckEmail returns, which shares nothing with the caller's. It holds
From and the other addresses as the email package normalizes them, an
empty list as nil, and the headers.

The subject is kept as given, not encoded as the SES sender sends one
that is not ASCII. The sender logs no message, and no part of one.

To read and empty the outbox:

- [Service.Messages](#Service.Messages) returns copies of the messages in the order they
were sent.
- [Service.Reset](#Service.Reset) empties the outbox.

Both work in any state of the sender, and the outbox outlives Close and
a restart.

A send stores nothing when:

- it finds the outbox holding `maxmessages` messages, or its message
would take it past `maxbytes`. It then fails with [ErrOutboxFull](#ErrOutboxFull).
- a Close canceled it, even when its gas.TemplateProvider ignored the
cancellation and rendered.

## Lifecycle

A successful Init logs `service initialized` at info level with `from`,
whether a default sender is set, `max_messages` and `max_bytes`. Init
on an initialized sender returns email.ErrAlreadyInitialized and
changes nothing. A failed Init leaves the sender as it was.

[Service.Close](#Service.Close) runs these steps, in order:

1. It makes the sender closed.
2. It waits for the sends in flight, such as a SendFromTemplate that
waits on its gas.TemplateProvider.
3. It logs `service closed` at info level.

When its context ends first, Close cancels the sends in flight, logs
`service closed, sends in flight canceled` at warn level, and returns
an error wrapping the context's error. Close on a sender that is not
initialized returns nil and logs nothing.

[New](#New)'s constructor fails with:

- email.ErrNilTemplates for a nil gas.TemplateProvider;
- email.ErrNilLogger for a nil logger;
- email.ErrNilConfig for WithConfig(nil).

A nil ConfigProvider is accepted, and Init then requires WithConfig.

## Readiness

[Service.CheckReady](#Service.CheckReady) does no I/O: it fails only when the sender is not
initialized or its context has ended.

## Concurrency

A Service is safe for concurrent use. Init and Close run one at a time.
The outbox is kept under a lock, which no send holds while it renders.

## Errors

The sentinel error of this package, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrOutboxFull](#ErrOutboxFull): the outbox holds `maxmessages` messages, or the
message would take it past `maxbytes`.

The other errors wrap a sentinel of the email package, as the email
package describes. Every error starts with [ServiceName](#ServiceName) and the
operation, `send` standing below for both send operations:

```go
gas/email/memory: template provider is nil
gas/email/memory: logger is nil
gas/email/memory: config is nil
gas/email/memory: init: no config provider
gas/email/memory: init: invalid config: Email.FromEmail must be one email address
gas/email/memory: init: service already initialized
gas/email/memory: init: context canceled
gas/email/memory: ready: service not initialized
gas/email/memory: send: message is nil
gas/email/memory: send: service not initialized
gas/email/memory: send: service closed
gas/email/memory: send: context canceled
gas/email/memory: send: no recipients
gas/email/memory: send: outbox full
gas/email/memory: send from template: template failed: HTML "welcome.html": execute failed
gas/email/memory: close: context deadline exceeded
```


## API reference

### Constants

<a id="DefaultMaxMessages"></a><a id="DefaultMaxBytes"></a><a id="MinMaxBytes"></a>

```go
const (
	// DefaultMaxMessages is the most messages the outbox holds in
	// DefaultConfig.
	DefaultMaxMessages = 10000
	// DefaultMaxBytes is the most bytes the outbox holds in
	// DefaultConfig: 256 MiB.
	DefaultMaxBytes = 256 << 20
	// MinMaxBytes is the least the MaxBytes setting allows: 1 MiB.
	MinMaxBytes = 1 << 20
)
```

<a id="ServiceName"></a>

```go
const ServiceName = "gas/email/memory"
```

ServiceName is the name of the memory sender, returned by Service.Name
and prefixed to every error the sender returns.

### Variables

<a id="ErrOutboxFull"></a>

```go
var ErrOutboxFull = errors.New("outbox full")
```

ErrOutboxFull indicates that a send found the outbox holding
MaxMessages messages, or that its message would take the outbox past
MaxBytes.

<a id="New"></a>

#### func New

```go
func New(
	opts ...Option,
) func(gas.TemplateProvider, gas.ConfigProvider, gas.Logger) (*Service, error)
```

New returns the constructor of a Service with opts applied, in the shape
the gas container expects. The constructor returns an error wrapping
email.ErrNilTemplates for a nil TemplateProvider, email.ErrNilLogger
for a nil logger, and email.ErrNilConfig for WithConfig(nil); a nil
ConfigProvider is accepted, and Init then requires WithConfig.

<a id="Config"></a>

### type Config

```go
type Config struct {
	// Email holds the settings.
	Email Settings
}
```

Config holds the memory sender's configuration, read from the `email`
section.

<a id="DefaultConfig"></a>

#### func DefaultConfig

```go
func DefaultConfig() *Config
```

DefaultConfig returns the configuration a sender starts from before
binding: no default sender, DefaultMaxMessages and DefaultMaxBytes.

<a id="Option"></a>

### type Option

```go
type Option func(*Service)
```

Option configures a Service. Options only record what they are given;
the constructor and Init check it.

<a id="WithConfig"></a>

#### func WithConfig

```go
func WithConfig(cfg *Config) Option
```

WithConfig makes Init use a copy of cfg instead of binding the
configuration from the ConfigProvider. Init copies \*cfg each time it
runs and never changes it; the copy is checked against its validate
tags as a bound configuration is. A nil cfg makes the constructor fail
with email.ErrNilConfig.

Default: bind the `email` section from the ConfigProvider over
DefaultConfig.

<a id="Service"></a>

### type Service

```go
type Service struct {
	// contains filtered or unexported fields
}
```

Service is an email sender that keeps what it sends in an outbox in
the process's memory, as described in the package documentation. It is
safe for concurrent use.

<a id="Service.CheckReady"></a>

#### func (*Service) CheckReady

```go
func (s *Service) CheckReady(ctx context.Context) error
```

CheckReady reports readiness without I/O: an error wrapping
email.ErrNotInitialized or email.ErrClosed when the sender is not
initialized, the context's error when ctx has ended, and else nil.

<a id="Service.Close"></a>

#### func (*Service) Close

```go
func (s *Service) Close(ctx context.Context) error
```

Close makes every later call but Init return an error wrapping
email.ErrClosed, and waits for every send in flight to return, as
described in the package documentation. When ctx ends first, it
cancels the sends in flight, which return email.ErrClosed, and returns
an error wrapping ctx's error. The outbox stays. Close on a sender
that is not initialized returns nil and logs nothing.

<a id="Service.Config"></a>

#### func (*Service) Config

```go
func (s *Service) Config() Config
```

Config returns a copy of the configuration the last successful Init
resolved, defaults included, or the zero Config before one. A failed
Init and Close leave it as it was. Config holds no slice, map or
pointer, so the copy shares nothing with the sender.

<a id="Service.Init"></a>

#### func (*Service) Init

```go
func (s *Service) Init(ctx context.Context) error
```

Init resolves the configuration and opens the sender, as described in
the package documentation. On an initialized sender it returns
email.ErrAlreadyInitialized and changes nothing.

<a id="Service.Messages"></a>

#### func (*Service) Messages

```go
func (s *Service) Messages() []gas.Email
```

Messages returns copies of the messages in the outbox, in the order they
were sent, as normalized: changing what it returns changes no message
of the outbox. It works in any state of the sender.

<a id="Service.Name"></a>

#### func (*Service) Name

```go
func (*Service) Name() string
```

Name returns ServiceName.

<a id="Service.Reset"></a>

#### func (*Service) Reset

```go
func (s *Service) Reset()
```

Reset empties the outbox. It works in any state of the sender.

<a id="Service.Send"></a>

#### func (*Service) Send

```go
func (s *Service) Send(ctx context.Context, msg *gas.Email) error
```

Send checks msg as email.CheckEmail does and stores a normalized copy
of it in the outbox, as described in the package documentation.

<a id="Service.SendFromTemplate"></a>

#### func (*Service) SendFromTemplate

```go
func (s *Service) SendFromTemplate(ctx context.Context, msg *gas.TemplatedEmail) error
```

SendFromTemplate renders msg into a copy, as the email package
describes under Templates, and sends the copy as Send does. It never
changes msg.

<a id="Settings"></a>

### type Settings

```go
type Settings struct {
	// FromEmail is the sender of a message whose From is empty; empty is
	// none.
	FromEmail string
	// MaxMessages is the most messages the outbox holds, at least 1.
	MaxMessages int `validate:"min=1"`
	// MaxBytes is the most bytes the messages of the outbox hold, each
	// counted as email.MessageSize estimates it, at least MinMaxBytes.
	MaxBytes int `validate:"min=1048576"`
}
```

Settings are the memory sender's settings, as described in the package
documentation.
