fakeemail

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 17 Imported by: 0

README

fake-email-go

Go Reference CI

The official Go client for the fake-email.pro API: create a disposable mailbox, wait for the email, get the one-time code or the magic link. Built for end-to-end tests of signup, OTP and password-reset flows with go test, playwright-go and chromedp.

mb, _ := mail.Mailboxes.Create(ctx, nil)
// ...sign up with mb.Address in your app...
code, _ := mail.WaitForCode(ctx, mb.Address, nil) // "048213"
  • Standard library only, Go 1.23+, context.Context on every call
  • Long-poll waiting: the message is returned within about a second of delivery, no polling loops in your tests
  • Codes and confirm links are extracted on the server
  • Retries on rate limits and transient errors, honoring Retry-After
  • Typed errors that work with errors.As

API reference: api.fake-email.pro/docs · Guides: fake-email.pro/api/docs/sdks · Go docs: pkg.go.dev

Install

go get github.com/fake-email-pro/fake-email-go
import fakeemail "github.com/fake-email-pro/fake-email-go"

Get an API key

  1. Sign in at fake-email.pro. Any account can use the API, the free plan included.
  2. Open Settings → API keys (fake-email.pro/settings/api-keys) and create a key. It starts with fep_ and is shown only once.
  3. Put it in the environment of your tests (and in your CI secrets):
export FAKE_EMAIL_API_KEY=fep_...

The client reads FAKE_EMAIL_API_KEY by default. A bigger monthly quota and higher limits come with PRO.

Server-side only. Never ship the key to browser code (a WebAssembly build included): anyone could read it, and the API does not allow cross-origin requests (no CORS).

Quickstart

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"time"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

func main() {
	ctx := context.Background()
	mail, err := fakeemail.NewClient() // or fakeemail.NewClient(fakeemail.WithAPIKey("fep_..."))
	if err != nil {
		log.Fatal(err)
	}

	// 1. A fresh address, valid for 24 hours
	mb, err := mail.Mailboxes.Create(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer mail.Mailboxes.Delete(ctx, mb.Address)

	// 2. Make your app send an email to it
	if _, err := http.PostForm("https://your-app.example/signup", url.Values{"email": {mb.Address}}); err != nil {
		log.Fatal(err)
	}

	// 3. Wait for the email and take the code
	code, err := mail.WaitForCode(ctx, mb.Address, &fakeemail.WaitOptions{Timeout: 60 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(code)

	// Or the confirm / magic link
	// link, err := mail.WaitForLink(ctx, mb.Address, nil)
}

WaitForCode returns the code found in the email when it was delivered. If none was found then, it reads the full message and takes its first code; an email with no code at all is skipped and the wait goes on. WaitForLink does the same with the confirm link.

go test

A fresh mailbox per test, deleted when the test ends:

// signup_test.go
package app_test

import (
	"context"
	"testing"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

var mail = mustClient()

func mustClient() *fakeemail.Client {
	c, err := fakeemail.NewClient() // FAKE_EMAIL_API_KEY from the environment of `go test`
	if err != nil {
		panic(err)
	}
	return c
}

func newInbox(t *testing.T) string {
	t.Helper()
	mb, err := mail.Mailboxes.Create(context.Background(), nil)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { mail.Mailboxes.Delete(context.Background(), mb.Address) })
	return mb.Address
}

func TestSignupSendsACode(t *testing.T) {
	inbox := newInbox(t)
	signUp(t, inbox) // your app under test

	code, err := mail.WaitForCode(t.Context(), inbox, &fakeemail.WaitOptions{Subject: "verification"})
	if err != nil {
		t.Fatal(err)
	}
	confirm(t, inbox, code)
}

go test stops a test binary after 10 minutes by default, far above the 60 s the wait helpers use; t.Context() (Go 1.24+) is cancelled when the test ends, so a wait never outlives its test.

Playwright

With playwright-go (import "github.com/mxschmitt/playwright-go"):

func TestSignUpWithAnEmailCode(t *testing.T) {
	must := func(err error) {
		t.Helper()
		if err != nil {
			t.Fatal(err)
		}
	}
	inbox := newInbox(t) // from the go test section above

	pw, err := playwright.Run()
	must(err)
	defer pw.Stop()
	browser, err := pw.Chromium.Launch()
	must(err)
	defer browser.Close()
	page, err := browser.NewPage()
	must(err)

	_, err = page.Goto("http://localhost:3000/signup")
	must(err)
	must(page.GetByLabel("Email").Fill(inbox))
	must(page.GetByRole("button", playwright.PageGetByRoleOptions{Name: "Send code"}).Click())

	code, err := mail.WaitForCode(t.Context(), inbox, &fakeemail.WaitOptions{Subject: "verification"})
	must(err)

	must(page.GetByLabel("Code").Fill(code))
	must(page.GetByRole("button", playwright.PageGetByRoleOptions{Name: "Continue"}).Click())
	must(playwright.NewPlaywrightAssertions().Locator(page.GetByText("Welcome")).ToBeVisible())
}

The same works with chromedp: run the actions that submit the form, then call mail.WaitForCode between two chromedp.Run calls.

Waiting for messages

message, err := mail.WaitForMessage(ctx, address, &fakeemail.WaitOptions{
	Timeout: 60 * time.Second, // client-side deadline, then *WaitTimeoutError
	From:    "acme.example",   // case-insensitive substring of the sender address
	Subject: "verify",         // case-insensitive substring of the subject
	Match:   func(m *fakeemail.SimpleMessage) bool { return m.AttachmentsCount > 0 }, // any extra check
})
message.Code        // *string: "048213" or nil
message.ConfirmLink // *string: "https://..." or nil

From and Subject are filtered on the server. A message that fails Match is skipped and the wait continues with the next one. Under the hood the client repeats the server's long poll (up to 60 s each) until the deadline.

The next message

Without After, the wait returns the earliest message in the mailbox, even one that arrived before you started waiting, so nothing is lost. To wait for a newer one, for example after "Resend code", pass the previous message's id:

first, err := mail.WaitForMessage(ctx, address, nil)
// ...click "Resend code"...
second, err := mail.WaitForMessage(ctx, address, &fakeemail.WaitOptions{After: first.ID})

AfterTime takes a time.Time instead (After also takes an RFC 3339 string): "messages that arrived after this moment" by the server's clock. Prefer a message id: it is exact, while a time depends on clock skew. Do not pass a message's CreatedAt: a second message in the same millisecond would be skipped.

An After id that is no longer in the mailbox (you deleted that message) is a *NotFoundError: if your tests delete processed messages, wait without After.

Cancelling

Every method takes a context.Context first. A cancelled or expired context ends the call, the wait helpers included, and the method returns ctx.Err() as is:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
code, err := mail.WaitForCode(ctx, address, nil)
if errors.Is(err, context.DeadlineExceeded) { /* your context ran out first */ }

Messages, attachments and raw EML

page, err := mail.Messages.List(ctx, address, &fakeemail.PageParams{Page: 0, Size: 20}) // newest first
for m, err := range mail.Messages.ListAll(ctx, address, nil) {
	if err != nil {
		return err
	}
	fmt.Println(m.ID, m.CreatedAt)
}

full, err := mail.Messages.Get(ctx, address, message.ID)
full.HTML; full.Text; full.Codes; full.Links; full.Attachments

att, err := mail.Messages.Attachment(ctx, address, message.ID, full.Attachments[0].ID)
// att.Data []byte, att.ContentType string, att.FileName *string (from Content-Disposition)

eml, err := mail.Messages.Raw(ctx, address, message.ID) // []byte, the message as received

err = mail.Messages.Delete(ctx, address, message.ID)

One long poll without the client-side loop: mail.Messages.Wait(ctx, address, &fakeemail.WaitParams{Timeout: 30 * time.Second, After: id}) returns the message, or nil, nil when the server timeout passed (204).

Mailboxes, domains and limits

mail.Mailboxes.Create(ctx, nil)                                                      // random address on a random domain
mail.Mailboxes.Create(ctx, &fakeemail.CreateMailboxParams{Domain: "example.org"})   // random address on that domain
mail.Mailboxes.Create(ctx, &fakeemail.CreateMailboxParams{LocalPart: "signup-test", Domain: "example.org"}) // exactly that

mail.Mailboxes.Get(ctx, address)
mail.Mailboxes.List(ctx, &fakeemail.PageParams{Page: 0, Size: 50})
for mb, err := range mail.Mailboxes.ListAll(ctx, nil) { /* ... */ }
mail.Mailboxes.Delete(ctx, address) // messages are erased; the address is never issued again

domains, err := mail.Domains.List(ctx) // []Domain{{Name: "example.org", Type: "PUBLIC"}, ...}
limits, err := mail.Limits.Get(ctx)    // Quota, RequestsPerMinute, ConcurrentWaits, Storage, MailboxTTLSeconds

A mailbox accepts mail for 24 hours and cannot be renewed; after that it answers 404. Each created mailbox spends one unit of your monthly quota (deleting it does not give it back). Custom local parts depend on the plan.

Parameter structs treat a zero value as unset, and nil params are allowed everywhere. In the models, nullable API fields are pointers (Subject *string, From *Sender), timestamps are time.Time, and enums are string types (BodyState, DomainType, ErrorCode) whose constants list the known values; a value added by a newer server passes through as is.

Errors

Errors from the server are *fakeemail.APIError with Status, Code (the API's error field), Message, Body, Header and RateLimit. Statuses with their own meaning come as a type that embeds *APIError and unwraps to it, so errors.As matches both the specific type and *APIError:

Type When
*BadRequestError 400 bad_request: an invalid parameter or body
*AuthenticationError 401 unauthorized: missing, unknown, revoked or expired key
*QuotaExhaustedError 402 quota_exhausted: monthly mailbox quota spent (Limit, Used, ResetsAt, UpgradeURL)
*PermissionDeniedError 403 plan_forbidden: the plan does not allow this
*NotFoundError 404 not_found: mailbox expired, deleted or not yours; no such message
*ConflictError 409 address_taken: the address was issued before
*RateLimitError 429: Code is rate_limit_exceeded or too_many_waits; RetryAfter
*InternalServerError 5xx
*APIError any other non-2xx status
*APIConnectionError no response (DNS, refused, reset); unwraps to the transport's error
*APITimeoutError an HTTP attempt took longer than the timeout; unwraps to *APIConnectionError
*WaitTimeoutError WaitForMessage / WaitForCode / WaitForLink reached their deadline

Every one of them implements fakeemail.FakeEmailError. A cancelled context is the exception: you get ctx.Err() itself (context.Canceled or context.DeadlineExceeded).

mb, err := mail.Mailboxes.Create(ctx, nil)

var quota *fakeemail.QuotaExhaustedError
if errors.As(err, &quota) {
	log.Fatalf("Quota %d/%d, renews %s. More: %s", quota.Used, quota.Limit, quota.ResetsAt, quota.UpgradeURL)
}

var apiErr *fakeemail.APIError
if errors.As(err, &apiErr) && apiErr.Code == fakeemail.ErrorCodePlanForbidden {
	// apiErr.Status == 403; err.Error() == "403 plan_forbidden: plan does not allow custom localPart"
}

var timeout *fakeemail.WaitTimeoutError
if errors.As(err, &timeout) {
	log.Printf("nothing in %s within %s", timeout.Address, timeout.Timeout)
}
Retries and rate limits

The client retries up to WithMaxRetries times (default 2):

  • 429 and 503, for every method: the server refuses these before doing anything. The wait is Retry-After (at most 60 s).
  • 502, 504, timeouts and network errors, for GET and DELETE only, never for POST (a mailbox could be created twice). Exponential backoff with jitter: 0.5 s, 1 s, 2 s, ... up to 8 s.

Inside WaitForMessage and friends, a 429 keeps being waited out while the deadline allows, and no retry is started that would end past the deadline.

Your plan's numbers are in mail.Limits.Get(ctx). Every *APIError carries the window state from the X-RateLimit-* headers as RateLimit (*RateLimitInfo{Limit, Remaining, Reset}, or nil when the server did not send them). Each wait request counts once, however long it is held open.

Configuration

mail, err := fakeemail.NewClient(
	fakeemail.WithAPIKey("fep_..."),                       // default: $FAKE_EMAIL_API_KEY
	fakeemail.WithBaseURL("https://api.fake-email.pro"),   // default
	fakeemail.WithTimeout(30*time.Second),                 // per HTTP attempt; a wait request gets its server timeout + 10 s
	fakeemail.WithMaxRetries(2),
	fakeemail.WithHTTPClient(&http.Client{Transport: myTransport}), // proxies, custom TLS, tracing
	fakeemail.WithUserAgent("my-e2e-suite/1.0"),           // appended to "fake-email-pro-go/<version>"
)

NewClient returns fakeemail.ErrMissingAPIKey when there is no key. The client is safe for concurrent use: create it once and share it between tests.

Every method also takes per-call options last: fakeemail.WithRequestTimeout(d) and fakeemail.WithRequestMaxRetries(n).

License

MIT

Documentation

Overview

Package fakeemail is the official Go client for the fake-email.pro Public API: create a disposable mailbox, wait for the email, get the one-time code or the magic link. It is built for end-to-end tests of signup, OTP and password-reset flows.

client, err := fakeemail.NewClient() // reads FAKE_EMAIL_API_KEY
if err != nil {
	return err
}
mb, err := client.Mailboxes.Create(ctx, nil)
if err != nil {
	return err
}
// ...sign up with mb.Address in your app...
code, err := client.WaitForCode(ctx, mb.Address, nil) // "048213"

Every method takes a context.Context first; a cancelled context ends the call with ctx.Err(). Errors from the server are *APIError or one of the status types that embed it (*NotFoundError, *RateLimitError, ...), so both errors.As(err, &notFound) and errors.As(err, &apiErr) work.

The client is safe for concurrent use. Use it from server-side code only: the API key must never reach a browser.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

func main() {
	ctx := context.Background()
	client, err := fakeemail.NewClient() // reads FAKE_EMAIL_API_KEY
	if err != nil {
		log.Fatal(err)
	}

	// 1. A fresh address, valid for 24 hours
	mb, err := client.Mailboxes.Create(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Mailboxes.Delete(ctx, mb.Address)

	// 2. Make your app send an email to mb.Address, then
	// 3. wait for the email and take the code
	code, err := client.WaitForCode(ctx, mb.Address, &fakeemail.WaitOptions{Timeout: 60 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(code)
}

Index

Examples

Constants

View Source
const (
	// DefaultBaseURL is the production API.
	DefaultBaseURL = "https://api.fake-email.pro"
	// DefaultTimeout is the limit of one HTTP attempt. A wait request gets its server timeout + 10 s instead.
	DefaultTimeout = 30 * time.Second
	// DefaultMaxRetries is how many times a retryable failure is repeated.
	DefaultMaxRetries = 2
)
View Source
const Version = "0.1.0"

Version is the version of this SDK, sent in the User-Agent header as "fake-email-pro-go/<Version>". The release workflow checks that the tag vX.Y.Z equals it.

Variables

View Source
var ErrMissingAPIKey error = &clientError{
	msg: "missing API key: pass fakeemail.WithAPIKey or set FAKE_EMAIL_API_KEY (create one at https://fake-email.pro/settings/api-keys)",
}

ErrMissingAPIKey is returned by NewClient when no key is given and FAKE_EMAIL_API_KEY is empty.

Functions

This section is empty.

Types

type APIConnectionError

type APIConnectionError struct {
	Message string
	Err     error
}

APIConnectionError means the request got no response (DNS, refused connection, reset). Err is the underlying error from the transport.

func (*APIConnectionError) Error

func (e *APIConnectionError) Error() string

func (*APIConnectionError) Unwrap

func (e *APIConnectionError) Unwrap() error

Unwrap returns the transport's error.

type APIError

type APIError struct {
	// Status is the HTTP status.
	Status int
	// Code is the error field of the body; "" when the body is not the JSON envelope (e.g. a proxy's 502).
	Code ErrorCode
	// Message is the message field of the body, or "HTTP <status>" when the body is not the envelope.
	Message string
	// Body is the parsed JSON body (map[string]any, ...), or the raw text when it is not JSON, or nil when
	// empty.
	Body any
	// Header holds the response headers.
	Header http.Header
	// RateLimit is from X-RateLimit-*; nil when the response did not carry them (the state is unknown, not
	// zero).
	RateLimit *RateLimitInfo
}

APIError means the server answered with a non-2xx status. A status with its own type (400, 401, 402, 403, 404, 409, 429, 5xx) comes as that type, which embeds *APIError and unwraps to it, so errors.As(err, &apiErr) matches every one of them.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

func main() {
	ctx := context.Background()
	client, _ := fakeemail.NewClient()

	_, err := client.Mailboxes.Create(ctx, nil)

	var quota *fakeemail.QuotaExhaustedError
	var apiErr *fakeemail.APIError
	switch {
	case errors.As(err, &quota):
		fmt.Printf("quota %d/%d, renews %s. More: %s\n", quota.Used, quota.Limit, quota.ResetsAt, quota.UpgradeURL)
	case errors.As(err, &apiErr): // any other status
		fmt.Println(apiErr.Status, apiErr.Code, apiErr.RateLimit)
	case errors.Is(err, context.Canceled):
		fmt.Println("cancelled")
	case err != nil:
		fmt.Println(err) // *APIConnectionError, *APITimeoutError
	}
}

func (*APIError) Error

func (e *APIError) Error() string

Error formats as "<status> <code>: <message>", or "<status>: HTTP <status>" when the body is not the envelope.

type APITimeoutError

type APITimeoutError struct {
	*APIConnectionError
}

APITimeoutError means an HTTP attempt took longer than the client's timeout. It unwraps to its *APIConnectionError, which unwraps to the transport's error.

func (*APITimeoutError) Timeout

func (e *APITimeoutError) Timeout() bool

Timeout reports true, like net.Error.

func (*APITimeoutError) Unwrap

func (e *APITimeoutError) Unwrap() error

Unwrap returns the embedded *APIConnectionError.

type Attachment

type Attachment struct {
	ID string `json:"id"`
	// ContentType is the MIME type as declared by the sender, without parameters.
	ContentType string `json:"contentType"`
	// FileName is the file name as declared by the sender; nil if there is none.
	FileName *string `json:"fileName"`
	// SizeBytes is the size of the decoded content.
	SizeBytes int64 `json:"sizeBytes"`
}

Attachment describes an attachment of a DetailedMessage; download it with MessagesService.Attachment.

type AuthenticationError

type AuthenticationError struct{ *APIError }

AuthenticationError is 401 unauthorized: the key is missing, unknown, revoked or expired.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap returns the embedded *APIError.

type BadRequestError

type BadRequestError struct{ *APIError }

BadRequestError is 400 bad_request: a parameter or the body is invalid.

func (*BadRequestError) Unwrap

func (e *BadRequestError) Unwrap() error

Unwrap returns the embedded *APIError.

type BodyState

type BodyState string

BodyState tells what the server kept of a message.

const (
	// BodyStateStored: parsed; the body and the EML are kept.
	BodyStateStored BodyState = "STORED"
	// BodyStateUnparsed: could not be parsed; only the EML is kept (no body, attachments, from or subject).
	BodyStateUnparsed BodyState = "UNPARSED"
	// BodyStateOverflow: larger than the account's whole storage; only the headers are kept, no EML, SizeBytes 0.
	BodyStateOverflow BodyState = "OVERFLOW"
)

type Client

type Client struct {
	Mailboxes *MailboxesService
	Messages  *MessagesService
	Domains   *DomainsService
	Limits    *LimitsService
	// contains filtered or unexported fields
}

Client is a client for the fake-email.pro Public API. Create it with NewClient; it is safe for concurrent use. Server-side only: the key must never reach browser code (the API has no CORS).

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a client. It fails with ErrMissingAPIKey when no key is given and FAKE_EMAIL_API_KEY is empty.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the API origin the client sends requests to, without a trailing slash.

func (*Client) WaitForCode

func (c *Client) WaitForCode(ctx context.Context, address string, opts *WaitOptions) (string, error)

WaitForCode waits for a message with a one-time code and returns the code. It uses the code found on delivery, else the first code of the full message; a message without any code is skipped.

func (c *Client) WaitForLink(ctx context.Context, address string, opts *WaitOptions) (string, error)

WaitForLink waits for a message with a confirm / sign-in link and returns its URL. It uses the link found on delivery, else the first link of the full message; a message without links is skipped.

func (*Client) WaitForMessage

func (c *Client) WaitForMessage(ctx context.Context, address string, opts *WaitOptions) (*SimpleMessage, error)

WaitForMessage waits until a matching message arrives, repeating the server's long poll (up to 60 s each) until opts.Timeout. At the deadline it returns a *WaitTimeoutError.

Example
package main

import (
	"context"
	"fmt"
	"log"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

func main() {
	ctx := context.Background()
	client, _ := fakeemail.NewClient()

	first, err := client.WaitForMessage(ctx, "signup-test@example.org", &fakeemail.WaitOptions{
		From:    "acme.example", // case-insensitive substring of the sender address
		Subject: "verify",       // case-insensitive substring of the subject
		Match:   func(m *fakeemail.SimpleMessage) bool { return m.AttachmentsCount == 0 },
	})
	if err != nil {
		log.Fatal(err)
	}
	// ...click "Resend code" in your app, then wait for a newer message:
	second, err := client.WaitForMessage(ctx, "signup-test@example.org", &fakeemail.WaitOptions{After: first.ID})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(second.ID)
}

type ConflictError

type ConflictError struct{ *APIError }

ConflictError is 409 address_taken: the address was issued before, to anyone.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the embedded *APIError.

type CreateMailboxParams

type CreateMailboxParams struct {
	// LocalPart is the exact local part; it requires Domain and a plan that allows custom local parts.
	LocalPart string
	// Domain is a domain from Domains.List; random if unset.
	Domain string
}

CreateMailboxParams are the fields of a new mailbox. A zero value means unset; nil params are allowed.

type DetailedMessage

type DetailedMessage struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	// From is nil for BodyStateUnparsed and for a message without From.
	From *Sender `json:"from"`
	// Subject is nil if there is none or the message was not parsed.
	Subject   *string   `json:"subject"`
	BodyState BodyState `json:"bodyState"`
	// HTML is the HTML part; nil if there is none, and for BodyStateUnparsed / BodyStateOverflow.
	HTML *string `json:"html"`
	// Text is the plain-text part (never derived from the HTML); nil if there is none.
	Text *string `json:"text"`
	// Attachments are in the order of the message's parts.
	Attachments []Attachment `json:"attachments"`
	// Codes are one-time codes, computed on read; Codes[0] is the best guess.
	Codes []string `json:"codes"`
	// Links are ranked by how likely they are to "confirm / sign in"; Links[0] is the best guess.
	Links []Link `json:"links"`
}

DetailedMessage is the full message: bodies, attachments, every code and link.

type Domain

type Domain struct {
	// Name is the domain name in lowercase.
	Name string     `json:"name"`
	Type DomainType `json:"type"`
}

Domain is a domain you can create a mailbox on.

type DomainType

type DomainType string

DomainType is the kind of a domain. PREMIUM is visible only to plans that allow premium domains.

const (
	DomainTypePublic  DomainType = "PUBLIC"
	DomainTypePremium DomainType = "PREMIUM"
)

type DomainsService

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

DomainsService lists domains. Use it as client.Domains.

func (*DomainsService) List

func (s *DomainsService) List(ctx context.Context, opts ...RequestOption) ([]Domain, error)

List returns the domains you can create a mailbox on, sorted by name.

type DownloadedAttachment

type DownloadedAttachment struct {
	// Data is the decoded bytes.
	Data []byte
	// ContentType is from the Content-Type header (application/octet-stream if absent).
	ContentType string
	// FileName is from Content-Disposition (RFC 5987 filename* preferred); nil if absent.
	FileName *string
}

DownloadedAttachment is the content of an attachment.

type ErrorCode

type ErrorCode string

ErrorCode is the error field of the API's error envelope; tell errors apart by it.

const (
	ErrorCodeBadRequest           ErrorCode = "bad_request"
	ErrorCodeUnauthorized         ErrorCode = "unauthorized"
	ErrorCodeQuotaExhausted       ErrorCode = "quota_exhausted"
	ErrorCodeForbidden            ErrorCode = "forbidden"
	ErrorCodeOAuthRequired        ErrorCode = "oauth_required"
	ErrorCodePlanForbidden        ErrorCode = "plan_forbidden"
	ErrorCodePlanLimitExceeded    ErrorCode = "plan_limit_exceeded"
	ErrorCodeNotFound             ErrorCode = "not_found"
	ErrorCodeMethodNotAllowed     ErrorCode = "method_not_allowed"
	ErrorCodeAddressTaken         ErrorCode = "address_taken"
	ErrorCodeDomainUnavailable    ErrorCode = "domain_unavailable"
	ErrorCodeConfirmationRequired ErrorCode = "confirmation_required"
	ErrorCodeInvalidState         ErrorCode = "invalid_state"
	ErrorCodeDomainExists         ErrorCode = "domain_exists"
	ErrorCodePayloadTooLarge      ErrorCode = "payload_too_large"
	ErrorCodeUnsupportedMediaType ErrorCode = "unsupported_media_type"
	ErrorCodeRateLimitExceeded    ErrorCode = "rate_limit_exceeded"
	ErrorCodeTooManyWaits         ErrorCode = "too_many_waits"
	ErrorCodeInternalServerError  ErrorCode = "internal_server_error"
)

type FakeEmailError

type FakeEmailError interface {
	error
	// contains filtered or unexported methods
}

FakeEmailError is implemented by every error this SDK returns, except ctx.Err() when the context ends:

var fe fakeemail.FakeEmailError
if errors.As(err, &fe) { ... }

The name matches the base error of the other fake-email.pro SDKs.

type InternalServerError

type InternalServerError struct{ *APIError }

InternalServerError is any 5xx, including a proxy's 502 during a server restart and 503 service unavailable.

func (*InternalServerError) Unwrap

func (e *InternalServerError) Unwrap() error

Unwrap returns the embedded *APIError.

type Limits

type Limits struct {
	Quota Quota `json:"quota"`
	// RequestsPerMinute is the rate limit per user (X-RateLimit-Limit).
	RequestsPerMinute int `json:"requestsPerMinute"`
	// ConcurrentWaits is how many wait requests may be held open at once per user.
	ConcurrentWaits int     `json:"concurrentWaits"`
	Storage         Storage `json:"storage"`
	// MailboxTTLSeconds is how long a mailbox accepts mail after creation.
	MailboxTTLSeconds int `json:"mailboxTtlSeconds"`
}

Limits are the numbers that apply to you right now, under your current plan.

type LimitsService

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

LimitsService reads your plan's numbers. Use it as client.Limits.

func (*LimitsService) Get

func (s *LimitsService) Get(ctx context.Context, opts ...RequestOption) (*Limits, error)

Get returns your quota, rate limit, concurrent waits, storage and mailbox lifetime. It does not spend quota.

type Link struct {
	// URL is http:// or https:// only.
	URL string `json:"url"`
	// Text is the visible link text (or the image's alt); nil for bare URLs.
	Text *string `json:"text"`
}

Link is a link found in a message.

type ListAllParams

type ListAllParams struct {
	// Size is the page size used while iterating, 1..50 (default 50).
	Size int
}

ListAllParams configure ListAll. nil is allowed.

type Mailbox

type Mailbox struct {
	// Address is localPart@domain in lowercase.
	Address string `json:"address"`
	// ActiveSince is the creation time.
	ActiveSince time.Time `json:"activeSince"`
	// ExpiresAt is when the mailbox stops accepting mail; from then on it and its messages are 404.
	ExpiresAt time.Time `json:"expiresAt"`
	// StorageUsedBytes is the sum of SizeBytes of the mailbox's messages.
	StorageUsedBytes int64 `json:"storageUsedBytes"`
	// MessagesCount is the number of messages in the mailbox.
	MessagesCount int `json:"messagesCount"`
}

Mailbox is an active API mailbox. It accepts mail for 24 hours after creation, then is deleted together with its messages.

type MailboxPage

type MailboxPage = Page[Mailbox]

MailboxPage is a page of mailboxes.

type MailboxesService

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

MailboxesService creates, lists, reads and deletes mailboxes. Use it as client.Mailboxes.

func (*MailboxesService) Create

func (s *MailboxesService) Create(ctx context.Context, params *CreateMailboxParams, opts ...RequestOption) (*Mailbox, error)

Create creates a mailbox, spending one unit of the monthly quota. With nil params: a random address on a random domain.

func (*MailboxesService) Delete

func (s *MailboxesService) Delete(ctx context.Context, address string, opts ...RequestOption) error

Delete deletes the mailbox and its messages. The address is never issued again; the quota is not given back.

func (*MailboxesService) Get

func (s *MailboxesService) Get(ctx context.Context, address string, opts ...RequestOption) (*Mailbox, error)

Get returns an active mailbox of yours.

func (*MailboxesService) List

func (s *MailboxesService) List(ctx context.Context, params *PageParams, opts ...RequestOption) (*MailboxPage, error)

List returns one page of active mailboxes, newest first.

func (*MailboxesService) ListAll

func (s *MailboxesService) ListAll(ctx context.Context, params *ListAllParams, opts ...RequestOption) iter.Seq2[Mailbox, error]

ListAll yields every active mailbox, fetching pages as needed. On an error it yields the error once and stops.

for mb, err := range client.Mailboxes.ListAll(ctx, nil) {
	if err != nil {
		return err
	}
	fmt.Println(mb.Address)
}
Example
package main

import (
	"context"
	"fmt"
	"log"

	fakeemail "github.com/fake-email-pro/fake-email-go"
)

func main() {
	ctx := context.Background()
	client, _ := fakeemail.NewClient()

	for mb, err := range client.Mailboxes.ListAll(ctx, nil) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(mb.Address, mb.ExpiresAt)
	}
}

type MessagePage

type MessagePage = Page[SimpleMessage]

MessagePage is a page of messages.

type MessagesService

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

MessagesService lists, waits for, reads and deletes messages. Use it as client.Messages.

func (*MessagesService) Attachment

func (s *MessagesService) Attachment(ctx context.Context, address, id, attachmentID string, opts ...RequestOption) (*DownloadedAttachment, error)

Attachment returns the decoded bytes of an attachment, with its type and file name.

func (*MessagesService) Delete

func (s *MessagesService) Delete(ctx context.Context, address, id string, opts ...RequestOption) error

Delete deletes a message.

func (*MessagesService) Get

func (s *MessagesService) Get(ctx context.Context, address, id string, opts ...RequestOption) (*DetailedMessage, error)

Get returns the full message: bodies, attachments, every code and link.

func (*MessagesService) List

func (s *MessagesService) List(ctx context.Context, address string, params *PageParams, opts ...RequestOption) (*MessagePage, error)

List returns one page of the mailbox's messages, newest first. To watch for new mail use Wait or Client.WaitForMessage, not polling.

func (*MessagesService) ListAll

func (s *MessagesService) ListAll(ctx context.Context, address string, params *ListAllParams, opts ...RequestOption) iter.Seq2[SimpleMessage, error]

ListAll yields every message of the mailbox, newest first, fetching pages as needed. On an error it yields the error once and stops.

func (*MessagesService) Raw

func (s *MessagesService) Raw(ctx context.Context, address, id string, opts ...RequestOption) ([]byte, error)

Raw returns the message's EML, byte for byte.

func (*MessagesService) Wait

func (s *MessagesService) Wait(ctx context.Context, address string, params *WaitParams, opts ...RequestOption) (*SimpleMessage, error)

Wait is one long poll: it returns the earliest matching message (strictly after After), or (nil, nil) when the server's timeout passed without one (204). For a loop with a client-side deadline use Client.WaitForMessage.

The HTTP attempt is given the server timeout + 10 s unless WithRequestTimeout overrides it.

type NotFoundError

type NotFoundError struct{ *APIError }

NotFoundError is 404 not_found: the mailbox is not an active API mailbox of yours (expired, deleted), or the message or attachment is not there.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the embedded *APIError.

type Option

type Option func(*config)

Option configures a Client in NewClient.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key (fep_…). The default is the FAKE_EMAIL_API_KEY environment variable.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets the API origin, optionally with a path prefix. Default DefaultBaseURL; trailing slashes are trimmed.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the *http.Client that sends requests (default: a new client with http.DefaultTransport). Its Timeout, if set, applies on top of the SDK's per-attempt timeout.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a retryable failure is repeated (default 2): 429 and 503 always, 502, 504, timeouts and network errors for GET and DELETE only.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the limit of each HTTP attempt (default 30 s). A wait request gets its server timeout + 10 s instead.

func WithUserAgent

func WithUserAgent(suffix string) Option

WithUserAgent appends a token to the SDK's own User-Agent, e.g. "my-e2e-suite/1.0".

type Page

type Page[T any] struct {
	Content []T `json:"content"`
	// Page is the zero-based page number.
	Page          int   `json:"page"`
	Size          int   `json:"size"`
	TotalPages    int   `json:"totalPages"`
	TotalElements int64 `json:"totalElements"`
}

Page is one page of a list, newest first.

type PageParams

type PageParams struct {
	// Page is the zero-based page number (default 0).
	Page int
	// Size is the page size, 1..50 (server default 20).
	Size int
}

PageParams select one page of a list. A zero value means unset (the server's default); nil is allowed.

type PermissionDeniedError

type PermissionDeniedError struct{ *APIError }

PermissionDeniedError is 403 plan_forbidden: the plan has no API access, or does not allow a custom local part.

func (*PermissionDeniedError) Unwrap

func (e *PermissionDeniedError) Unwrap() error

Unwrap returns the embedded *APIError.

type Quota

type Quota struct {
	// Limit is API mailboxes per month on the plan.
	Limit int `json:"limit"`
	// Used counts API mailboxes created since the 1st of the month in UTC, deleted ones included.
	Used int `json:"used"`
	// ResetsAt is the 1st of the next month, 00:00 UTC.
	ResetsAt time.Time `json:"resetsAt"`
}

Quota is the monthly quota of API mailboxes (calendar month in UTC).

type QuotaExhaustedError

type QuotaExhaustedError struct {
	*APIError
	// Limit is API mailboxes per month on the plan.
	Limit int
	// Used is API mailboxes created this month, deleted ones included.
	Used int
	// ResetsAt is when the quota renews: the 1st of next month, 00:00 UTC.
	ResetsAt time.Time
	// UpgradeURL is the pricing page.
	UpgradeURL string
}

QuotaExhaustedError is 402 quota_exhausted: the monthly mailbox quota is spent. It is not retried: the quota renews at ResetsAt. A field the body did not carry is left at its zero value.

func (*QuotaExhaustedError) Unwrap

func (e *QuotaExhaustedError) Unwrap() error

Unwrap returns the embedded *APIError.

type RateLimitError

type RateLimitError struct {
	*APIError
	// RetryAfter is from the Retry-After header, rounded up to whole seconds; 0 if absent.
	RetryAfter time.Duration
}

RateLimitError is 429: Code is ErrorCodeRateLimitExceeded (requests per minute) or ErrorCodeTooManyWaits (concurrent waits).

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the embedded *APIError.

type RateLimitInfo

type RateLimitInfo struct {
	// Limit is requests per minute on the plan.
	Limit int
	// Remaining is requests left in the current window.
	Remaining int
	// Reset is the end of the window.
	Reset time.Time
}

RateLimitInfo is the rate-limit window state from the X-RateLimit-* headers.

type RequestOption

type RequestOption func(*requestConfig)

RequestOption overrides a client setting for one call. Every method accepts them last.

func WithRequestMaxRetries

func WithRequestMaxRetries(n int) RequestOption

WithRequestMaxRetries overrides the client's maxRetries for this call.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) RequestOption

WithRequestTimeout overrides the client's per-attempt timeout for this call.

type Sender

type Sender struct {
	Name    *string `json:"name"`
	Address string  `json:"address"`
}

Sender is the sender from the From header.

type SimpleMessage

type SimpleMessage struct {
	ID string `json:"id"`
	// MailboxAddress is the address of the message's mailbox.
	MailboxAddress string `json:"mailboxAddress"`
	// CreatedAt is the delivery time. Do not use it as After: pass the message's ID instead.
	CreatedAt time.Time `json:"createdAt"`
	// SizeBytes is the EML size; 0 for BodyStateOverflow.
	SizeBytes int64 `json:"sizeBytes"`
	// From is nil for BodyStateUnparsed and for a message without From.
	From *Sender `json:"from"`
	// Subject is nil if there is none or the message was not parsed. Never "".
	Subject          *string   `json:"subject"`
	BodyState        BodyState `json:"bodyState"`
	AttachmentsCount int       `json:"attachmentsCount"`
	// Code is the best one-time code, computed on delivery (= Codes[0] of the full message); nil if none.
	Code *string `json:"code"`
	// ConfirmLink is the best "confirm / sign in" link, computed on delivery (= Links[0].URL); nil if none.
	ConfirmLink *string `json:"confirmLink"`
}

SimpleMessage is a message in a list and in the wait response.

type Storage

type Storage struct {
	UsedBytes  int64 `json:"usedBytes"`
	LimitBytes int64 `json:"limitBytes"`
}

Storage is the storage taken by the account's messages, across all mailboxes.

type WaitOptions

type WaitOptions struct {
	// Timeout is the client-side deadline for the whole wait (default 60 s). Past it the helpers return a
	// *WaitTimeoutError.
	Timeout time.Duration
	// After returns only messages strictly after this message id or RFC 3339 time (server clock).
	After string
	// AfterTime is After as a time. Set After or AfterTime, not both.
	AfterTime time.Time
	// From is a case-insensitive substring of the sender address (server-side filter).
	From string
	// Subject is a case-insensitive substring of the subject (server-side filter).
	Subject string
	// Match is a client-side filter; a message that fails it is skipped and the wait continues after it.
	Match func(*SimpleMessage) bool
}

WaitOptions configure WaitForMessage, WaitForCode and WaitForLink. A zero value means unset; nil is allowed.

type WaitParams

type WaitParams struct {
	// Timeout is how long the server holds the request, 1..60 s, sent in whole seconds rounded up (server
	// default 30 s).
	Timeout time.Duration
	// After returns only messages strictly after this message id (to continue after a message you got) or
	// RFC 3339 time (by the server's clock). Do not pass a message's CreatedAt.
	After string
	// AfterTime is After as a time, sent in UTC with milliseconds. Set After or AfterTime, not both.
	AfterTime time.Time
	// From is a case-insensitive substring of the sender address.
	From string
	// Subject is a case-insensitive substring of the subject.
	Subject string
}

WaitParams configure one long poll. A zero value means unset; nil is allowed.

type WaitTimeoutError

type WaitTimeoutError struct {
	Address string
	Timeout time.Duration
}

WaitTimeoutError means WaitForMessage, WaitForCode or WaitForLink reached their deadline without a matching message.

func (*WaitTimeoutError) Error

func (e *WaitTimeoutError) Error() string

Jump to

Keyboard shortcuts

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