mailfloss

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 14 Imported by: 0

README

Mailfloss Go SDK

The official Go SDK for the Mailfloss email verification API. Zero third-party dependencies — standard library only.

Installation

go get github.com/mailfloss/mailfloss-go

Requires Go 1.24+.

Authentication

Every request is authenticated with your Mailfloss API key, sent as Authorization: Bearer <key>. Provide it either explicitly:

client, err := mailfloss.New(mailfloss.WithAPIKey("mf_rk_..."))

or via the environment:

export MAILFLOSS_API_KEY="mf_rk_..."
client, err := mailfloss.New() // reads MAILFLOSS_API_KEY

New returns a clear configuration error when no key is available.

Quickstart

Verify a single email — GET /v1/verify
package main

import (
	"context"
	"fmt"
	"log"

	mailfloss "github.com/mailfloss/mailfloss-go"
)

func main() {
	client, err := mailfloss.New() // uses MAILFLOSS_API_KEY
	if err != nil {
		log.Fatal(err)
	}

	res, err := client.Verify.Check(context.Background(), mailfloss.VerifyParams{
		Email: "jane@example.com",
	})
	if err != nil {
		log.Fatal(err)
	}

	// status is one of: passed, undeliverable, risky, unknown
	fmt.Printf("email=%s status=%s reason=%s passed=%t\n",
		res.Email, res.Status, res.Reason, res.Passed)
	if res.Suggestion != "" {
		fmt.Printf("did you mean %s?\n", res.Suggestion)
	}
}
Batch verification — POST /v1/batch-verify
job, err := client.BatchVerify.Create(ctx, mailfloss.BatchVerifyCreateParams{
	Emails:     []string{"jane@example.com", "noreply@example.com"},
	WebhookURL: "https://example.com/hooks/mailfloss", // optional: omit to poll
})
if err != nil {
	log.Fatal(err)
}

// Poll for progress...
status, err := client.BatchVerify.Status(ctx, job.ID)
fmt.Printf("job %s: %s (%.0f%%)\n", job.ID, status.Status, status.Progress)

// ...then page through the results.
page, err := client.BatchVerify.Results(ctx, job.ID, mailfloss.BatchVerifyResultsParams{
	PerPage: 1000,
})
for _, r := range page.Results {
	fmt.Printf("%s -> %s (%s)\n", r.Email, r.Status, r.Reason)
}

Services

Service Methods Endpoints
client.Verify Check GET /verify
client.BatchVerify Create, Status, Results, Cancel POST /batch-verify, GET /batch-verify/{id}/status, GET /batch-verify/{id}/results, POST /batch-verify/{id}/cancel
client.Jobs List, Get GET /jobs, GET /jobs/{id}
client.Users List, Get GET /users, GET /users/{user_id}
client.Reports Usage GET /reports/usage
client.CheckKey Get (takes CheckKeyParams: APIKey, PublicKey, CheckPlan, GetToken, CheckCredits) GET /check-key
client.Account Get, Update GET /account, PATCH /account
client.Organization Get GET /organization
client.Integrations List, Get, CreateConnection, GetConnection, UpdateConnection, DeleteConnection, SyncConnection, TestConnection, ListKeywords, AddKeywords, DeleteKeyword /integrations...
client.Erasures Create POST /erasures
Pagination

List endpoints return a {data, pagination} envelope:

params := mailfloss.JobsListParams{PerPage: 100}
for {
	page, err := client.Jobs.List(ctx, params)
	if err != nil {
		log.Fatal(err)
	}
	for _, job := range page.Data {
		fmt.Println(job.ID, job.Status)
	}
	if !page.Pagination.HasMore {
		break
	}
	params.Cursor = *page.Pagination.NextCursor
}
Updating the account (omit vs clear)

PATCH /v1/account is a merge-patch: omitted fields are left unchanged, and nullable fields accept explicit JSON null to clear the stored value. The SDK models this with mailfloss.Optional[T]:

acct, err := client.Account.Update(ctx, mailfloss.AccountUpdateParams{
	Organization: mailfloss.Set("Acme Corp"),   // set a new value
	Phone:        mailfloss.Null[string](),     // clear the stored phone
	// VATID omitted (zero value) — left unchanged
})

Error handling

Non-2xx responses return a *mailfloss.Error:

_, err := client.Verify.Check(ctx, mailfloss.VerifyParams{Email: "x"})
var apiErr *mailfloss.Error
if errors.As(err, &apiErr) {
	// Branch on the stable code, not the message.
	fmt.Println(apiErr.Status, apiErr.Code, apiErr.Message, apiErr.RequestID)
}

Retries

The client automatically retries requests that fail with 429, 5xx, or a transport error (default 3 retries, configurable via mailfloss.WithMaxRetries). A Retry-After header is honored; otherwise exponential backoff with full jitter is applied (base 0.5s, factor 2, capped at 8s).

Idempotency

Every POST automatically carries a UUID v4 Idempotency-Key, reused across retries. Override it per call:

job, err := client.BatchVerify.Create(ctx, params,
	mailfloss.WithIdempotencyKey("order-8472-verify"))

Configuration

client, err := mailfloss.New(
	mailfloss.WithAPIKey("mf_rk_..."),
	mailfloss.WithBaseURL("https://api.mailfloss.com/v1"), // default
	mailfloss.WithMaxRetries(5),
	mailfloss.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
)

License

MIT — see LICENSE.

Documentation

Overview

Package mailfloss is the official Go SDK for the Mailfloss email verification API (https://api.mailfloss.com/v1).

Construct a client with New, authenticating with an API key passed via WithAPIKey or the MAILFLOSS_API_KEY environment variable:

client, err := mailfloss.New(mailfloss.WithAPIKey("mf_rk_..."))
if err != nil { ... }
res, err := client.Verify.Check(ctx, mailfloss.VerifyParams{Email: "jane@example.com"})

Index

Constants

View Source
const EnvAPIKey = "MAILFLOSS_API_KEY"

EnvAPIKey is the environment variable consulted for the API key when WithAPIKey is not supplied.

View Source
const Version = "0.1.0"

Version is the SDK version, sent in the User-Agent header.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	// ID is the opaque, stable holder handle (usr_...); it matches the
	// is_primary member from GET /v1/users. Do not parse it.
	ID string `json:"id"`
	// Name is the holder display name, or nil when unset.
	Name *string `json:"name"`
	// Email is the primary email on the account.
	Email string `json:"email"`
	// EmailVerified is true when the holder has confirmed their email.
	EmailVerified bool `json:"email_verified"`
	// TwoFactorEnabled is true when TOTP 2FA is enabled.
	TwoFactorEnabled bool `json:"two_factor_enabled"`
	// IdentityVerified is tri-state: "verified", "requires_input", or nil
	// when verification was never requested (the common case).
	IdentityVerified *string `json:"identity_verified"`
	// Phone is the contact phone in E.164 form, or nil when unset.
	Phone *string `json:"phone"`
	// Organization is the company name, or nil.
	Organization *string `json:"organization"`
	// VATID is the VAT identification number (EU customers), or nil.
	VATID *string `json:"vat_id"`
	// Country is the holder country (ISO code) when on file, else nil.
	Country *string `json:"country"`
	// Address is the billing/contact address, or nil when none on file.
	Address *Address `json:"address"`
	// Notifications are the email-notification preferences; always present.
	Notifications Notifications `json:"notifications"`
	// CreatedAt is the ISO 8601 UTC signup timestamp, or nil when unknown.
	CreatedAt *string `json:"created_at"`
}

Account is the account holder this API key belongs to.

type AccountService

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

AccountService reads and updates the account holder this API key belongs to.

func (*AccountService) Get

func (s *AccountService) Get(ctx context.Context, opts ...RequestOption) (*Account, error)

Get returns the account holder. GET /v1/account.

func (*AccountService) Update

func (s *AccountService) Update(ctx context.Context, params AccountUpdateParams, opts ...RequestOption) (*Account, error)

Update applies a partial update and returns the refreshed account. PATCH /v1/account.

type AccountUpdateParams

type AccountUpdateParams struct {
	// Name sets the holder display name (1-200 chars). Not nullable.
	Name *string `json:"name,omitempty"`
	// Phone sets or clears (Null) the contact phone.
	Phone Optional[string] `json:"phone,omitzero"`
	// Organization sets or clears (Null) the company name.
	Organization Optional[string] `json:"organization,omitzero"`
	// VATID sets or clears (Null) the VAT identification number.
	VATID Optional[string] `json:"vat_id,omitzero"`
	// Country sets or clears (Null) the country (ISO code).
	Country Optional[string] `json:"country,omitzero"`
	// Address partially updates the address; omitted sub-fields are left
	// unchanged.
	Address *AddressUpdateParams `json:"address,omitempty"`
	// Notifications partially updates notification preferences.
	Notifications *NotificationsUpdateParams `json:"notifications,omitempty"`
}

AccountUpdateParams is the JSON merge-patch body for PATCH /v1/account. Omitted fields are left unchanged. Nullable fields use Optional: mailfloss.Set("v") sets a value, mailfloss.Null[string]() sends explicit JSON null to clear it, and the zero value omits the field. Email, password, and 2FA are not updatable here.

type Address

type Address struct {
	Line1      *string `json:"line1"`
	Line2      *string `json:"line2"`
	City       *string `json:"city"`
	State      *string `json:"state"`
	PostalCode *string `json:"postal_code"`
	Country    *string `json:"country"`
}

Address is a billing/contact address. Individual sub-fields may be nil.

type AddressUpdateParams

type AddressUpdateParams struct {
	Line1      Optional[string] `json:"line1,omitzero"`
	Line2      Optional[string] `json:"line2,omitzero"`
	City       Optional[string] `json:"city,omitzero"`
	State      Optional[string] `json:"state,omitzero"`
	PostalCode Optional[string] `json:"postal_code,omitzero"`
	Country    Optional[string] `json:"country,omitzero"`
}

AddressUpdateParams partially updates the billing/contact address. Every sub-field is nullable: Set to change, Null to clear, zero value to leave unchanged.

type BatchVerifyCancelResult

type BatchVerifyCancelResult struct {
	Success bool `json:"success"`
}

BatchVerifyCancelResult confirms a cancel request.

type BatchVerifyCreateParams

type BatchVerifyCreateParams struct {
	// Emails are the addresses to verify.
	Emails []string `json:"emails"`
	// WebhookURL is an optional callback URL. When the batch job finishes,
	// Mailfloss sends a POST to it with the completed job. Omit to poll.
	WebhookURL string `json:"webhook_url,omitempty"`
}

BatchVerifyCreateParams is the request body for POST /v1/batch-verify.

type BatchVerifyJob

type BatchVerifyJob struct {
	// ID is the job identifier; use it with Status, Results, and Cancel,
	// or with the Jobs service.
	ID string `json:"id"`
}

BatchVerifyJob is the acknowledgement returned when a batch job is accepted.

type BatchVerifyResults

type BatchVerifyResults struct {
	ID      string         `json:"id"`
	Results []VerifyResult `json:"results"`
}

BatchVerifyResults is one page of verification results for a job.

type BatchVerifyResultsParams

type BatchVerifyResultsParams struct {
	// PerPage is the number of results per page, capped at 1000.
	PerPage int
	// Next is the pagination cursor; omit on the first call.
	Next string
}

BatchVerifyResultsParams are the pagination query parameters for GET /v1/batch-verify/{id}/results.

type BatchVerifyService

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

BatchVerifyService submits and manages batch verification jobs.

func (*BatchVerifyService) Cancel

Cancel stops a queued or in-flight batch job. POST /v1/batch-verify/{id}/cancel.

func (*BatchVerifyService) Create

Create submits a batch verification job. POST /v1/batch-verify.

func (*BatchVerifyService) Results

Results returns one page of results for a completed batch job. GET /v1/batch-verify/{id}/results.

func (*BatchVerifyService) Status

Status returns the progress of a batch job. GET /v1/batch-verify/{id}/status.

type BatchVerifyStatus

type BatchVerifyStatus struct {
	Status string `json:"status"`
	// Progress is the completion fraction/percentage reported by the API.
	Progress float64 `json:"progress"`
}

BatchVerifyStatus is the progress snapshot for a batch job.

type CheckKeyParams

type CheckKeyParams struct {
	// APIKey verifies the supplied key (instead of the bearer key) and
	// returns its account info. Provide this or PublicKey, not both.
	APIKey string
	// PublicKey is the widget/browser-side alternative to APIKey.
	PublicKey string
	// CheckPlan asks for plan details in the response.
	CheckPlan string
	// GetToken asks for a short-lived token in the response.
	GetToken string
	// CheckCredits asks for remaining-credit details in the response.
	CheckCredits string
}

CheckKeyParams are the optional query parameters for GET /v1/check-key. The zero value asks the API to validate the bearer key on the request.

type CheckKeyResult

type CheckKeyResult struct {
	Name         string  `json:"name"`
	Organization string  `json:"organization"`
	PlanType     string  `json:"planType"`
	FreeMatches  float64 `json:"freeMatches"`
	ExtraCredits float64 `json:"extraCredits"`
}

CheckKeyResult describes the key and the account it belongs to.

type CheckKeyService

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

CheckKeyService validates the configured API key.

func (*CheckKeyService) Get

Get validates the API key and returns account context. GET /v1/check-key.

type Client

type Client struct {

	// Services.
	Verify       *VerifyService
	BatchVerify  *BatchVerifyService
	Jobs         *JobsService
	Users        *UsersService
	Reports      *ReportsService
	CheckKey     *CheckKeyService
	Account      *AccountService
	Organization *OrganizationService
	Integrations *IntegrationsService
	Erasures     *ErasuresService
	// contains filtered or unexported fields
}

Client is the Mailfloss API client. Create one with New.

func New

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

New builds a Client. It returns an error when no API key is configured via WithAPIKey or the MAILFLOSS_API_KEY environment variable.

type Connection

type Connection struct {
	// ID is the connection-stable identifier.
	ID string `json:"id"`
	// Name is the customer-set display name (registry fallback when unset).
	Name string `json:"name"`
	// Status is "active" or "disconnected".
	Status string `json:"status"`
	// CreatedAt is the ISO 8601 UTC creation timestamp.
	CreatedAt *string `json:"created_at"`
	// LastSyncedAt is the ISO 8601 UTC timestamp of the most recent sync,
	// or nil.
	LastSyncedAt *string            `json:"last_synced_at"`
	Settings     ConnectionSettings `json:"settings"`
}

Connection is an active ESP connection.

type ConnectionChecks

type ConnectionChecks struct {
	Disposable     bool `json:"disposable"`
	Nonexistent    bool `json:"nonexistent"`
	Deactivated    bool `json:"deactivated"`
	InboxFull      bool `json:"inbox_full"`
	Bounced        bool `json:"bounced"`
	BannedWords    bool `json:"banned_words"`
	RoleBased      bool `json:"role_based"`
	Complainers    bool `json:"complainers"`
	Spam           bool `json:"spam"`
	FailedExchange bool `json:"failed_exchange"`
	Unverified     bool `json:"unverified"`
	AcceptAll      bool `json:"accept_all"`
}

ConnectionChecks are the 12 floss check gates.

type ConnectionChecksUpdate

type ConnectionChecksUpdate struct {
	Disposable     *bool `json:"disposable,omitempty"`
	Nonexistent    *bool `json:"nonexistent,omitempty"`
	Deactivated    *bool `json:"deactivated,omitempty"`
	InboxFull      *bool `json:"inbox_full,omitempty"`
	Bounced        *bool `json:"bounced,omitempty"`
	BannedWords    *bool `json:"banned_words,omitempty"`
	RoleBased      *bool `json:"role_based,omitempty"`
	Complainers    *bool `json:"complainers,omitempty"`
	Spam           *bool `json:"spam,omitempty"`
	FailedExchange *bool `json:"failed_exchange,omitempty"`
	Unverified     *bool `json:"unverified,omitempty"`
	AcceptAll      *bool `json:"accept_all,omitempty"`
}

ConnectionChecksUpdate is a partial set of the 12 floss check gates.

type ConnectionCreateParams

type ConnectionCreateParams struct {
	// Name is an optional display name; defaults to the ESP display name.
	Name string `json:"name,omitempty"`
	// Credentials are the per-type credentials (shape varies by ESP —
	// e.g. {"api_key": "..."} for Klaviyo, {"api_url": "...",
	// "api_key": "..."} for ActiveCampaign). Encrypted at rest; never
	// returned or logged.
	Credentials map[string]string `json:"credentials"`
}

ConnectionCreateParams is the request body for POST /v1/integrations/{type}/connections.

type ConnectionDeleted

type ConnectionDeleted struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	// Status is always "disconnected".
	Status string `json:"status"`
	// DisconnectedAt is the ISO 8601 UTC timestamp of the disconnect.
	DisconnectedAt string `json:"disconnected_at"`
}

ConnectionDeleted confirms a disconnect. A disconnect is permanent — to use the platform again, connect it anew.

type ConnectionSettings

type ConnectionSettings struct {
	// Aggressiveness is "normal", "aggressive", or "custom".
	Aggressiveness string `json:"aggressiveness"`
	// ManualMode holds failing addresses for dashboard review instead of
	// auto-removing them.
	ManualMode bool `json:"manual_mode"`
	// Autofloss is the scheduled daily auto-import + clean toggle.
	Autofloss bool `json:"autofloss"`
	// DecayProtection is the periodic re-verification toggle.
	DecayProtection bool `json:"decay_protection"`
	// Instafloss is the real-time verification toggle (read-only).
	Instafloss bool `json:"instafloss"`
	// Action is what Mailfloss does with invalid emails: "unsubscribe",
	// "delete", "update_tags", "update_custom_fields", "do_nothing", or
	// nil when unset.
	Action *string `json:"action"`
	// Checks are the 12 floss check gates; true means matching emails are
	// removed.
	Checks ConnectionChecks `json:"checks"`
	// BlacklistCount / WhitelistCount are the per-connection keyword rule
	// counts.
	BlacklistCount int `json:"blacklist_count"`
	WhitelistCount int `json:"whitelist_count"`
}

ConnectionSettings are a connection's floss settings.

type ConnectionTestResult

type ConnectionTestResult struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	// CredentialValid is true when the stored credentials were accepted by
	// the live ESP just now.
	CredentialValid bool `json:"credential_valid"`
	// TestedAt is the ISO 8601 UTC timestamp of the test.
	TestedAt string `json:"tested_at"`
	// Reason is present only when CredentialValid is false.
	Reason string `json:"reason,omitempty"`
}

ConnectionTestResult is the result of a credential health check.

type ConnectionUpdateParams

type ConnectionUpdateParams struct {
	// ManualMode toggles Manual Mode (mode-independent).
	ManualMode *bool `json:"manual_mode,omitempty"`
	// Aggressiveness sets the preset: "normal", "aggressive", or "custom".
	// Mutually exclusive with Checks in one request.
	Aggressiveness *string `json:"aggressiveness,omitempty"`
	// Checks partially updates the 12 gates; editing any gate switches the
	// connection to "custom" aggressiveness.
	Checks *ConnectionChecksUpdate `json:"checks,omitempty"`
	// Autofloss toggles Autofloss (paid-plan feature; 422 on unsupported
	// ESPs).
	Autofloss *bool `json:"autofloss,omitempty"`
	// DecayProtection toggles Decay Protection (paid-plan feature).
	DecayProtection *bool `json:"decay_protection,omitempty"`
	// Action sets the auto-action: "unsubscribe", "delete", "do_nothing",
	// or "update_custom_fields" (plan-gated). Setting an action turns off
	// Manual Mode.
	Action *string `json:"action,omitempty"`
}

ConnectionUpdateParams is the request body for PATCH /v1/integrations/{type}/connections/{id}. Omitted (nil) fields are left unchanged.

type DisconnectedConnection

type DisconnectedConnection struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Status is always "disconnected".
	Status    string  `json:"status"`
	CreatedAt *string `json:"created_at"`
	// DisconnectedAt is the ISO 8601 UTC timestamp of the disconnect.
	DisconnectedAt *string `json:"disconnected_at"`
}

DisconnectedConnection is a previously-connected, now-disconnected connection. Disconnect does not imply bad credentials — it is a deliberate soft-disable.

type ErasureCreateParams

type ErasureCreateParams struct {
	// Emails are the addresses to erase.
	Emails []string `json:"emails"`
	// WebhookURL is an optional callback URL; when the delete job
	// finishes, Mailfloss sends a POST to it.
	WebhookURL string `json:"webhook_url,omitempty"`
}

ErasureCreateParams is the request body for POST /v1/erasures.

type ErasureResult

type ErasureResult struct {
	Success bool `json:"success"`
}

ErasureResult confirms an accepted erasure request.

type ErasuresService

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

ErasuresService submits GDPR-style erasure (delete) requests.

func (*ErasuresService) Create

Create submits an erasure request. POST /v1/erasures.

type Error

type Error struct {
	// Status is the HTTP status code (e.g. 401, 429).
	Status int
	// Code is the stable machine-readable error code (e.g.
	// "invalid_api_key", "rate_limited"). Branch on this, not Message.
	Code string
	// Message is the human-readable description.
	Message string
	// Type is the error category (e.g. "authentication_error",
	// "rate_limit_error", "api_error").
	Type string
	// RequestID identifies the request for support (e.g. "req_1a2b3c4d5e6f").
	RequestID string
}

Error is the error returned for any non-2xx API response. It maps the API's standard error envelope: {"error": {"code", "message", "type", "request_id"}}. Use errors.As to inspect it:

var apiErr *mailfloss.Error
if errors.As(err, &apiErr) && apiErr.Status == 429 { ... }

func (*Error) Error

func (e *Error) Error() string

type Integration

type Integration struct {
	Type            string `json:"type"`
	Connected       bool   `json:"connected"`
	ConnectionCount int    `json:"connection_count"`
	// Connections are the active connections for this ESP.
	Connections []Connection `json:"connections"`
	// DisconnectedConnections are previously-connected, now soft-disabled
	// connections; empty when none.
	DisconnectedConnections []DisconnectedConnection `json:"disconnected_connections"`
}

Integration is the detail response of GET /v1/integrations/{type}.

type IntegrationPrimary

type IntegrationPrimary struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

IntegrationPrimary summarizes the primary connection of an ESP.

type IntegrationSummary

type IntegrationSummary struct {
	// Type is the ESP slug (e.g. "mailchimp", "klaviyo").
	Type string `json:"type"`
	// Connected reports whether the org has at least one active connection.
	Connected bool `json:"connected"`
	// ConnectionCount is the number of active connections; (org, type) is
	// 1:N.
	ConnectionCount int `json:"connection_count"`
	// Primary is a deterministic primary-connection summary (lowest
	// created_at), or nil when no active connections exist.
	Primary *IntegrationPrimary `json:"primary"`
	// DisconnectedCount is the number of soft-disabled connections not
	// counted in ConnectionCount.
	DisconnectedCount int `json:"disconnected_count"`
}

IntegrationSummary is one row of GET /v1/integrations.

type IntegrationsListParams

type IntegrationsListParams struct {
	PerPage int
	Cursor  string
}

IntegrationsListParams are the query parameters for GET /v1/integrations.

type IntegrationsService

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

IntegrationsService manages ESP integrations, their connections, and per-connection keyword rules.

func (*IntegrationsService) AddKeywords

func (s *IntegrationsService) AddKeywords(ctx context.Context, integrationType, id string, list KeywordList, params KeywordAddParams, opts ...RequestOption) (*KeywordRules, error)

AddKeywords adds keyword rules (1-1000, all-or-nothing) and returns the created rules. POST /v1/integrations/{type}/connections/{id}/keywords/{list}.

func (*IntegrationsService) CreateConnection

func (s *IntegrationsService) CreateConnection(ctx context.Context, integrationType string, params ConnectionCreateParams, opts ...RequestOption) (*Connection, error)

CreateConnection connects an ESP account. POST /v1/integrations/{type}/connections.

func (*IntegrationsService) DeleteConnection

func (s *IntegrationsService) DeleteConnection(ctx context.Context, integrationType, id string, opts ...RequestOption) (*ConnectionDeleted, error)

DeleteConnection disconnects a connection (permanent soft-disable). DELETE /v1/integrations/{type}/connections/{id}.

func (*IntegrationsService) DeleteKeyword

func (s *IntegrationsService) DeleteKeyword(ctx context.Context, integrationType, id string, list KeywordList, ruleID string, opts ...RequestOption) (*KeywordDeleted, error)

DeleteKeyword removes one keyword rule. DELETE /v1/integrations/{type}/connections/{id}/keywords/{list}/{ruleId}.

func (*IntegrationsService) Get

func (s *IntegrationsService) Get(ctx context.Context, integrationType string, opts ...RequestOption) (*Integration, error)

Get returns one integration with its connections. GET /v1/integrations/{type}.

func (*IntegrationsService) GetConnection

func (s *IntegrationsService) GetConnection(ctx context.Context, integrationType, id string, opts ...RequestOption) (*Connection, error)

GetConnection returns one connection. GET /v1/integrations/{type}/connections/{id}.

func (*IntegrationsService) List

List returns a page of integration summaries. GET /v1/integrations.

func (*IntegrationsService) ListKeywords

func (s *IntegrationsService) ListKeywords(ctx context.Context, integrationType, id string, list KeywordList, params KeywordsListParams, opts ...RequestOption) (*ListResponse[KeywordRule], error)

ListKeywords returns a page of keyword rules on a connection's blacklist or whitelist. GET /v1/integrations/{type}/connections/{id}/keywords/{list}.

func (*IntegrationsService) SyncConnection

func (s *IntegrationsService) SyncConnection(ctx context.Context, integrationType, id string, opts ...RequestOption) (*Connection, error)

SyncConnection triggers a refresh and returns the refreshed connection. POST /v1/integrations/{type}/connections/{id}/sync.

func (*IntegrationsService) TestConnection

func (s *IntegrationsService) TestConnection(ctx context.Context, integrationType, id string, opts ...RequestOption) (*ConnectionTestResult, error)

TestConnection performs a live credential health check. POST /v1/integrations/{type}/connections/{id}/test.

func (*IntegrationsService) UpdateConnection

func (s *IntegrationsService) UpdateConnection(ctx context.Context, integrationType, id string, params ConnectionUpdateParams, opts ...RequestOption) (*Connection, error)

UpdateConnection applies a partial settings update and returns the refreshed connection. PATCH /v1/integrations/{type}/connections/{id}.

type Job

type Job struct {
	// ID is the stable job identifier.
	ID string `json:"id"`
	// Status is the lifecycle state: "queued", "processing", "completed",
	// or "cancelled".
	Status string `json:"status"`
	// Source is how the job was submitted: "api", "csv", "zapier",
	// "widget", "input", or "integration".
	Source string `json:"source"`
	// SourceIntegration is the ESP slug when Source is "integration";
	// otherwise nil.
	SourceIntegration *string `json:"source_integration"`
	// CreatedAt is the ISO 8601 UTC submission time.
	CreatedAt *string `json:"created_at"`
	// FinishedAt is the ISO 8601 UTC completion time, or nil if not
	// finished.
	FinishedAt *string `json:"finished_at"`
	// Results holds verdict counts; nil unless Status is "completed".
	Results *JobResults `json:"results"`
}

Job is a verification job.

type JobResults

type JobResults struct {
	// Total is the number of emails in the job.
	Total int `json:"total"`
	// Processed is the number of emails verified.
	Processed int `json:"processed"`
	// Passed counts verified-good addresses (safe to send).
	Passed int `json:"passed"`
	// Failed counts everything NOT passed (undeliverable + risky +
	// unknown).
	Failed int `json:"failed"`
	// Undeliverable counts verified-bad addresses; a subset of Failed.
	Undeliverable int `json:"undeliverable"`
	// Risky counts deliverable-but-risky addresses; a subset of Failed.
	Risky int `json:"risky"`
	// Unknown counts undetermined addresses; a subset of Failed.
	Unknown int `json:"unknown"`
	// Reasons itemizes Failed per reason. Present on GET /v1/jobs/{id};
	// omitted (nil) in the GET /v1/jobs list.
	Reasons *ReasonCounts `json:"reasons,omitempty"`
}

JobResults holds the verdict counts of a completed job.

type JobsListParams

type JobsListParams struct {
	PerPage int
	Cursor  string
	// Source filters by submission source (e.g. "api", "csv").
	Source string
	// Status filters by lifecycle state (e.g. "completed").
	Status string
}

JobsListParams are the query parameters for GET /v1/jobs.

type JobsService

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

JobsService reads verification jobs across all sources.

func (*JobsService) Get

func (s *JobsService) Get(ctx context.Context, id string, opts ...RequestOption) (*Job, error)

Get returns one job, including the per-reason breakdown. GET /v1/jobs/{id}.

func (*JobsService) List

func (s *JobsService) List(ctx context.Context, params JobsListParams, opts ...RequestOption) (*ListResponse[Job], error)

List returns a page of jobs. GET /v1/jobs.

type KeywordAddParams

type KeywordAddParams struct {
	Rules []KeywordRuleInput `json:"rules"`
}

KeywordAddParams is the request body for adding keyword rules (1-1000, all-or-nothing).

type KeywordAppliesTo

type KeywordAppliesTo struct {
	// Localpart matches before the @.
	Localpart bool `json:"localpart"`
	// Domain matches after the @.
	Domain bool `json:"domain"`
	// Email matches the full address.
	Email bool `json:"email"`
}

KeywordAppliesTo selects the address segments a keyword rule matches.

type KeywordDeleted

type KeywordDeleted struct {
	Deleted bool   `json:"deleted"`
	ID      string `json:"id"`
}

KeywordDeleted confirms a rule deletion.

type KeywordList

type KeywordList string

KeywordList selects a per-connection keyword rule list.

const (
	// KeywordListBlacklist holds always-remove rules.
	KeywordListBlacklist KeywordList = "blacklist"
	// KeywordListWhitelist holds never-remove rules.
	KeywordListWhitelist KeywordList = "whitelist"
)

Keyword rule lists.

type KeywordRule

type KeywordRule struct {
	// ID is the stable rule identifier.
	ID string `json:"id"`
	// Keyword is the matched keyword/phrase (spaces stripped, case
	// preserved).
	Keyword string `json:"keyword"`
	// Match is "exact" or "contains".
	Match string `json:"match"`
	// AppliesTo selects which address segments the keyword matches.
	AppliesTo KeywordAppliesTo `json:"applies_to"`
}

KeywordRule is one keyword rule on a connection's blacklist or whitelist.

type KeywordRuleInput

type KeywordRuleInput struct {
	Keyword   string           `json:"keyword"`
	Match     string           `json:"match"`
	AppliesTo KeywordAppliesTo `json:"applies_to"`
}

KeywordRuleInput is one rule to add. At least one AppliesTo segment must be true.

type KeywordRules

type KeywordRules struct {
	Data []KeywordRule `json:"data"`
}

KeywordRules is the {data} envelope returned when adding rules.

type KeywordsListParams

type KeywordsListParams struct {
	PerPage int
	Cursor  string
}

KeywordsListParams are the query parameters for listing keyword rules.

type ListResponse

type ListResponse[T any] struct {
	Data       []T        `json:"data"`
	Pagination Pagination `json:"pagination"`
}

ListResponse is the standard {data, pagination} envelope returned by list endpoints.

type Notifications

type Notifications struct {
	// AfterFlossing sends a summary email after each completed floss.
	AfterFlossing bool `json:"after_flossing"`
	// WeeklyReport / MonthlyReport are periodic usage reports.
	WeeklyReport  bool `json:"weekly_report"`
	MonthlyReport bool `json:"monthly_report"`
	// PaymentReceipts sends billing receipts.
	PaymentReceipts bool `json:"payment_receipts"`
}

Notifications are the account's email-notification preferences.

type NotificationsUpdateParams

type NotificationsUpdateParams struct {
	AfterFlossing   *bool `json:"after_flossing,omitempty"`
	WeeklyReport    *bool `json:"weekly_report,omitempty"`
	MonthlyReport   *bool `json:"monthly_report,omitempty"`
	PaymentReceipts *bool `json:"payment_receipts,omitempty"`
}

NotificationsUpdateParams partially updates email-notification preferences.

type Option

type Option func(*Client)

Option configures the Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the API key explicitly. When omitted, the client falls back to the MAILFLOSS_API_KEY environment variable.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the default base URL (https://api.mailfloss.com/v1).

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies a custom *http.Client (e.g. with a custom RoundTripper or timeout).

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a request is retried after a 429, 5xx, or transport error. Default 3. Zero disables retries.

func WithSleep

func WithSleep(fn func(time.Duration)) Option

WithSleep injects the sleep function used between retries. Intended for tests; defaults to time.Sleep.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional is a tri-state JSON field for merge-patch bodies: absent (leave unchanged), explicit null (clear the value), or set. The zero value is "absent" and is dropped from request bodies via the `omitzero` struct tag.

func Null

func Null[T any]() Optional[T]

Null returns an Optional that serializes as explicit JSON null, which the API interprets as "clear this field".

func Set

func Set[T any](v T) Optional[T]

Set returns an Optional carrying v.

func (Optional[T]) IsNull

func (o Optional[T]) IsNull() bool

IsNull reports whether the field was set to explicit null.

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

IsZero reports whether the field is absent; encoding/json's `omitzero` uses it to drop the field from the body entirely.

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler so round-tripping works.

func (Optional[T]) Value

func (o Optional[T]) Value() (T, bool)

Value returns the carried value and whether one was set (false for both absent and null).

type Organization

type Organization struct {
	// Name is the org display name, or nil.
	Name *string `json:"name"`
	// Email is the account owner's email, or nil.
	Email *string `json:"email"`
	// Plan is the customer-facing plan slug (e.g. "free", "pro",
	// "business"); "unknown" when only a raw Stripe price ID is on file.
	Plan string `json:"plan"`
	// PlanID is the raw plan value — a friendly slug or a Stripe price ID
	// (price_*) — or nil. Prefer Plan for display.
	PlanID    *string             `json:"plan_id"`
	Credits   OrganizationCredits `json:"credits"`
	Usage     OrganizationUsage   `json:"usage"`
	Trial     OrganizationTrial   `json:"trial"`
	CreatedAt string              `json:"created_at"`
	// Status is the coarse org state: "active", "suspended", "paused",
	// "banned", "under_review", or "needs_identity_verification". Every
	// non-active state means API work requests are denied with 403.
	Status       string                   `json:"status"`
	Entitlements OrganizationEntitlements `json:"entitlements"`
}

Organization is the response of GET /v1/organization.

type OrganizationCredits

type OrganizationCredits struct {
	// Prepaid is the prepaid credit-pack balance.
	Prepaid int `json:"prepaid"`
	// Subscription is the plan's monthly allotment remaining this period.
	Subscription int `json:"subscription"`
	// Total is Prepaid + Subscription.
	Total int `json:"total"`
}

OrganizationCredits is the credit balance breakdown.

type OrganizationEntitlements

type OrganizationEntitlements struct {
	Webhooks    bool `json:"webhooks"`
	Instafloss  bool `json:"instafloss"`
	TypoFixer   bool `json:"typo_fixer"`
	Exclusions  bool `json:"exclusions"`
	UpdateTags  bool `json:"update_tags"`
	SSO         bool `json:"sso"`
	Autofloss   bool `json:"autofloss"`
	DecayBasic  bool `json:"decay_basic"`
	DecayCustom bool `json:"decay_custom"`
}

OrganizationEntitlements is the authoritative "what can this account use" feature map (true if native to the tier OR purchased as an add-on).

type OrganizationService

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

OrganizationService reads the organization (read-only; there is no PATCH — status and credits are server-managed).

func (*OrganizationService) Get

Get returns the organization. GET /v1/organization.

type OrganizationTrial

type OrganizationTrial struct {
	// Active reports whether the org is currently in its free trial. A
	// trialing org otherwise looks like a paid org, so read this field.
	Active bool `json:"active"`
	// StartedAt is the ISO 8601 UTC trial start, or nil when unknown.
	StartedAt *string `json:"started_at"`
	// EndsAt is the ESTIMATED ISO 8601 UTC trial end (start + 7 days), or
	// nil when not in trial / start unknown.
	EndsAt *string `json:"ends_at"`
}

OrganizationTrial is the free-trial state.

type OrganizationUsage

type OrganizationUsage struct {
	// CurrentPeriodStart is the ISO 8601 UTC start of the usage period.
	CurrentPeriodStart string `json:"current_period_start"`
	// CurrentPeriodEnd is the ISO 8601 UTC end (exclusive).
	CurrentPeriodEnd string `json:"current_period_end"`
	// CurrentPeriodTotal is credits consumed during the period.
	CurrentPeriodTotal int `json:"current_period_total"`
}

OrganizationUsage describes credits consumed in the current period.

type Pagination

type Pagination struct {
	// NextCursor is the opaque cursor for the next page; nil when HasMore
	// is false. Clients must not parse it.
	NextCursor *string `json:"next_cursor"`
	// HasMore reports whether more pages remain after this one.
	HasMore bool `json:"has_more"`
}

Pagination describes the cursor state of a paginated list response.

type ReasonCounts

type ReasonCounts struct {
	Invalid        int `json:"invalid"`
	Nonexistent    int `json:"nonexistent"`
	Deactivated    int `json:"deactivated"`
	InboxFull      int `json:"inbox_full"`
	Illegitimate   int `json:"illegitimate"`
	Spam           int `json:"spam"`
	RoleBased      int `json:"role_based"`
	BannedWords    int `json:"banned_words"`
	Disposable     int `json:"disposable"`
	FailedExchange int `json:"failed_exchange"`
	AcceptAll      int `json:"accept_all"`
	Unverified     int `json:"unverified"`
	Complained     int `json:"complained"`
	Bounced        int `json:"bounced"`
	Blacklisted    int `json:"blacklisted"`
	Available      int `json:"available"`
}

ReasonCounts holds per-reason verification counts. Every key is present; 0 when none.

type ReportsService

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

ReportsService reads usage reports.

func (*ReportsService) Usage

func (s *ReportsService) Usage(ctx context.Context, params UsageParams, opts ...RequestOption) (*UsageReport, error)

Usage returns a usage report. GET /v1/reports/usage.

type RequestOption

type RequestOption func(*requestOptions)

RequestOption customizes a single API call.

func WithIdempotencyKey

func WithIdempotencyKey(key string) RequestOption

WithIdempotencyKey overrides the auto-generated Idempotency-Key header sent on POST requests.

type UsageParams

type UsageParams struct {
	// Period is the calendar period (UTC): "this_week", "this_month",
	// "this_year", or "lifetime". Default this_month.
	Period string
	// ConnectionID scopes the report to one ESP connection. Per-connection
	// data exists only for this_week / this_month / this_year.
	ConnectionID string
}

UsageParams are the query parameters for GET /v1/reports/usage.

type UsageRange

type UsageRange struct {
	// Start is the period start, YYYY-MM-DD (UTC).
	Start string `json:"start"`
	// End is the period end, YYYY-MM-DD (UTC).
	End string `json:"end"`
}

UsageRange is the UTC calendar boundary of a usage report.

type UsageReport

type UsageReport struct {
	Period string `json:"period"`
	// ConnectionID is the ESP connection the report is scoped to, or nil
	// for an org-wide report.
	ConnectionID *string `json:"connection_id"`
	// Range holds the UTC calendar boundaries; nil for lifetime.
	Range *UsageRange `json:"range"`
	// Total is the authoritative number of emails verified in the period.
	Total int `json:"total"`
	// Statuses holds per-status counts; nil for lifetime.
	Statuses *UsageStatuses `json:"statuses"`
	// Reasons holds per-reason counts; nil for lifetime.
	Reasons *ReasonCounts `json:"reasons"`
}

UsageReport is the response of GET /v1/reports/usage.

type UsageStatuses

type UsageStatuses struct {
	Passed        int `json:"passed"`
	Failed        int `json:"failed"`
	Undeliverable int `json:"undeliverable"`
	Risky         int `json:"risky"`
	Unknown       int `json:"unknown"`
}

UsageStatuses holds per-status counts for the period.

type User

type User struct {
	// ID is the opaque, stable member handle (usr_...). Do not parse it.
	ID string `json:"id"`
	// Email is the member's email address.
	Email string `json:"email"`
	// Name is the display name, or nil when unset.
	Name *string `json:"name"`
	// Role is the permission level: "administrator" or "contributor".
	Role string `json:"role"`
	// IsPrimary is true for the account owner (exactly one per org).
	IsPrimary bool `json:"is_primary"`
	// Status is "active", "invited", or "paused".
	Status string `json:"status"`
	// CreatedAt is the ISO 8601 UTC account-creation time; nil only for
	// invited seats.
	CreatedAt *string `json:"created_at"`
}

User is an organization member (seat).

type UsersListParams

type UsersListParams struct {
	PerPage int
	Cursor  string
}

UsersListParams are the query parameters for GET /v1/users.

type UsersService

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

UsersService reads the organization's member roster.

func (*UsersService) Get

func (s *UsersService) Get(ctx context.Context, userID string, opts ...RequestOption) (*User, error)

Get returns one member by their usr_... handle. GET /v1/users/{user_id}.

func (*UsersService) List

func (s *UsersService) List(ctx context.Context, params UsersListParams, opts ...RequestOption) (*ListResponse[User], error)

List returns a page of members. GET /v1/users.

type VerifyParams

type VerifyParams struct {
	// Email is the email address to verify.
	Email string
	// Timeout is an optional per-request timeout, in seconds.
	Timeout *float64
}

VerifyParams are the query parameters for GET /v1/verify.

type VerifyResult

type VerifyResult struct {
	Email  string `json:"email"`
	Domain string `json:"domain,omitempty"`
	// Status is the verification verdict: "passed" (safe to send),
	// "undeliverable" (hard fail), "risky" (accept-all / role /
	// low-confidence), or "unknown".
	Status string `json:"status"`
	Reason string `json:"reason"`
	Passed bool   `json:"passed"`
	// Role reports whether the address is role-based (e.g. info@).
	Role *bool `json:"role,omitempty"`
	// Disposable reports whether the domain is a disposable provider.
	Disposable *bool `json:"disposable,omitempty"`
	// Free reports whether the domain is a free provider (e.g. gmail.com).
	Free *bool `json:"free,omitempty"`
	// Suggestion is a likely intended address when a typo is detected.
	Suggestion string `json:"suggestion,omitempty"`
	Meta       string `json:"meta,omitempty"`
}

VerifyResult is the verdict for a single email address.

type VerifyService

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

VerifyService verifies single email addresses in real time. GET /v1/verify.

func (*VerifyService) Check

func (s *VerifyService) Check(ctx context.Context, params VerifyParams, opts ...RequestOption) (*VerifyResult, error)

Check verifies a single email address.

Jump to

Keyboard shortcuts

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