truelist

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 9 Imported by: 0

README

truelist-go

Go SDK for the Truelist.io email validation API.

Installation

go get github.com/Truelist-io-Email-Validation/truelist-go

Requires Go 1.21 or later.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    truelist "github.com/Truelist-io-Email-Validation/truelist-go"
)

func main() {
    client := truelist.NewClient("your-api-key")

    result, err := client.Validate(context.Background(), "user@example.com")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.State)     // "ok"
    fmt.Println(result.IsValid()) // true
}

Methods

Validate

Email validation using your API key. Sends a POST to /api/v1/verify_inline with the email as a query parameter.

result, err := client.Validate(ctx, "user@example.com")
Account

Retrieve account information via GET /me.

account, err := client.Account(ctx)
fmt.Println(account.Email)                // "you@example.com"
fmt.Println(account.Name)                 // "Your Name"
fmt.Println(account.Account.PaymentPlan)  // "pro"

Result

The Result struct contains the full validation response:

Field Type JSON Field Description
Email string address The email address validated
Domain string domain The domain of the email
Canonical string canonical The canonical (local) part of the email
MxRecord *string mx_record MX record for the domain
FirstName *string first_name First name associated with the email
LastName *string last_name Last name associated with the email
State string email_state ok, email_invalid, or accept_all
SubState string email_sub_state Detailed sub-state (see below)
VerifiedAt string verified_at Timestamp of verification
Suggestion *string did_you_mean Suggested correction (e.g., typo fix)
Sub-States

email_ok, is_disposable, is_role, unknown_error, failed_smtp_check

Result Predicates
result.IsValid()      // State == "ok"
result.IsInvalid()    // State == "email_invalid"
result.IsAcceptAll()  // State == "accept_all"
result.IsDisposable() // SubState == "is_disposable"
result.IsRole()       // SubState == "is_role"

Account

The Account struct contains account information:

Field Type Description
Email string Account email
Name string Account holder name
UUID string Account UUID
TimeZone string Account time zone
IsAdminRole bool Whether the user is an admin
Account AccountInfo Nested account details

The AccountInfo struct:

Field Type Description
Name string Organization name
PaymentPlan string Current payment plan

Configuration Options

Option Default Description
WithBaseURL https://api.truelist.io Custom API base URL
WithTimeout 30s HTTP client timeout
WithMaxRetries 3 Max retries for transient errors (429, 5xx)
WithHTTPClient (default client) Custom *http.Client
client := truelist.NewClient("your-api-key",
    truelist.WithBaseURL("https://api.truelist.io"),
    truelist.WithTimeout(10 * time.Second),
    truelist.WithMaxRetries(2),
)

Error Handling

The SDK provides typed errors that can be checked with errors.Is:

result, err := client.Validate(ctx, "user@example.com")
if err != nil {
    if errors.Is(err, truelist.ErrAuthentication) {
        // Invalid API key (401) - never retried
    }
    if errors.Is(err, truelist.ErrRateLimit) {
        // Rate limit exceeded (429) - retried up to MaxRetries
    }
    if errors.Is(err, truelist.ErrAPI) {
        // Other API error (5xx) - retried up to MaxRetries
    }
}

For more details, use errors.As to access the *APIError:

var apiErr *truelist.APIError
if errors.As(err, &apiErr) {
    fmt.Println(apiErr.StatusCode) // 429
    fmt.Println(apiErr.Message)    // response body
}
Retry Behavior
  • 401 errors are never retried and always return ErrAuthentication.
  • 429 and 5xx errors are retried with exponential backoff up to MaxRetries times.
  • Set WithMaxRetries(0) to disable retries entirely.

Testing

Run the tests:

go test -race -v ./...
Mocking the Client

For testing your own code, create a test server with net/http/httptest:

package myapp

import (
    "context"
    "net/http"
    "net/http/httptest"
    "testing"

    truelist "github.com/Truelist-io-Email-Validation/truelist-go"
)

func TestMyValidation(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{"emails":[{"address":"user@example.com","domain":"example.com","canonical":"user","mx_record":null,"first_name":null,"last_name":null,"email_state":"ok","email_sub_state":"email_ok","verified_at":"2026-02-21T10:00:00.000Z","did_you_mean":null}]}`))
    }))
    defer srv.Close()

    client := truelist.NewClient("test-key",
        truelist.WithBaseURL(srv.URL),
        truelist.WithMaxRetries(0),
    )

    result, err := client.Validate(context.Background(), "user@example.com")
    if err != nil {
        t.Fatal(err)
    }
    if !result.IsValid() {
        t.Error("expected valid result")
    }
}

License

MIT

Documentation

Overview

Package truelist provides a Go client for the Truelist.io email validation API.

Create a client with your API key and use it to validate emails:

client := truelist.NewClient("your-api-key")
result, err := client.Validate(ctx, "user@example.com")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.IsValid())

Index

Constants

View Source
const (
	StateOK           = "ok"
	StateEmailInvalid = "email_invalid"
	StateAcceptAll    = "accept_all"
)

State constants for email validation results.

View Source
const (
	SubStateEmailOK      = "email_ok"
	SubStateIsDisposable = "is_disposable"
	SubStateIsRole       = "is_role"
	SubStateUnknownError = "unknown_error"
	SubStateFailedSMTP   = "failed_smtp_check"
)

SubState constants for email validation results.

Variables

View Source
var (
	// ErrAuthentication is returned when the API key is invalid or missing.
	ErrAuthentication = errors.New("authentication failed")

	// ErrRateLimit is returned when the API rate limit is exceeded.
	ErrRateLimit = errors.New("rate limit exceeded")

	// ErrAPI is returned for general API errors.
	ErrAPI = errors.New("API error")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Err        error
}

APIError wraps an API error with status code and message details.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type Account

type Account struct {
	Email       string      `json:"email"`
	Name        string      `json:"name"`
	UUID        string      `json:"uuid"`
	TimeZone    string      `json:"time_zone"`
	IsAdminRole bool        `json:"is_admin_role"`
	Account     AccountInfo `json:"account"`
}

Account represents the response from the account info endpoint.

type AccountInfo

type AccountInfo struct {
	Name        string `json:"name"`
	PaymentPlan string `json:"payment_plan"`
}

AccountInfo represents the nested account details.

type Client

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

Client is the Truelist API client.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new Truelist API client with the given API key.

func (*Client) Account

func (c *Client) Account(ctx context.Context) (*Account, error)

Account retrieves account information using the API key.

func (*Client) Validate

func (c *Client) Validate(ctx context.Context, email string) (*Result, error)

Validate performs email validation using the API key.

type Option

type Option func(*Client)

Option configures the Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom base URL for the API.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retries for transient errors (429, 5xx). Set to 0 to disable retries. Default is 3.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP client timeout.

type Result

type Result struct {
	Email      string  `json:"address"`
	Domain     string  `json:"domain"`
	Canonical  string  `json:"canonical"`
	MxRecord   *string `json:"mx_record"`
	FirstName  *string `json:"first_name"`
	LastName   *string `json:"last_name"`
	State      string  `json:"email_state"`
	SubState   string  `json:"email_sub_state"`
	VerifiedAt string  `json:"verified_at"`
	Suggestion *string `json:"did_you_mean"`
}

Result represents the response from an email validation request.

func (*Result) IsAcceptAll

func (r *Result) IsAcceptAll() bool

IsAcceptAll returns true if the email state is "accept_all".

func (*Result) IsDisposable

func (r *Result) IsDisposable() bool

IsDisposable returns true if the email sub-state is "is_disposable".

func (*Result) IsInvalid

func (r *Result) IsInvalid() bool

IsInvalid returns true if the email state is "email_invalid".

func (*Result) IsRole

func (r *Result) IsRole() bool

IsRole returns true if the email sub-state is "is_role".

func (*Result) IsValid

func (r *Result) IsValid() bool

IsValid returns true if the email state is "ok".

Jump to

Keyboard shortcuts

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