envloped

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 10 Imported by: 0

README

Envloped Go SDK

The official Go client library for the Envloped email API.

Installation

go get github.com/envloped/envloped-go

Requires Go 1.21 or later. Zero third-party dependencies.

Quick Start

package main

import (
    "fmt"
    "log"

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

func main() {
    client := envloped.NewClient("ev_your_api_key")

    resp, err := client.Emails.Send(&envloped.SendEmailRequest{
        From:    "hello@yourdomain.com",
        To:      []string{"user@example.com"},
        Subject: "Hello from Envloped",
        Html:    "<p>Welcome!</p>",
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Sent! Message ID:", resp.MessageId)
}

API Reference

Creating a Client
// Default client (production API)
client := envloped.NewClient("ev_your_api_key")

// Custom base URL (for testing or self-hosted)
client := envloped.NewClient("ev_your_api_key").
    WithBaseURL("https://your-api.example.com")

// Custom HTTP client (timeouts, proxies, etc.)
client := envloped.NewClient("ev_your_api_key").
    WithHTTPClient(&http.Client{Timeout: 10 * time.Second})
Sending Emails
resp, err := client.Emails.Send(&envloped.SendEmailRequest{
    From:    "My App <hello@yourdomain.com>",
    To:      []string{"user@example.com"},
    Subject: "Welcome!",
    Html:    "<h1>Hello</h1><p>Welcome to our app.</p>",
    Text:    "Hello\n\nWelcome to our app.", // optional fallback
})

Fields:

Field Type Required Description
From string Yes Sender address. Domain must be verified.
To []string Yes Recipient addresses.
Subject string Yes Email subject line.
Html string * HTML body. At least one of Html/Text required.
Text string * Plain text body. At least one of Html/Text required.

Response:

type SendEmailResponse struct {
    Success   bool   `json:"success"`
    MessageId string `json:"messageId"`
}
Ping

Check connectivity and API key validity:

pong, err := client.Ping()
fmt.Println(pong.Message)   // "pong"
fmt.Println(pong.CompanyID) // your company ID
Context Support

Every method has a WithContext variant for cancellation and deadlines:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

resp, err := client.Emails.SendWithContext(ctx, &envloped.SendEmailRequest{
    // ...
})

Error Handling

All API errors are returned as typed errors that support errors.Is() and errors.As():

resp, err := client.Emails.Send(params)
if err != nil {
    // Sentinel error checks
    if errors.Is(err, envloped.ErrUnauthorized) {
        log.Fatal("Invalid API key")
    }
    if errors.Is(err, envloped.ErrForbidden) {
        log.Fatal("Domain not verified")
    }
    if errors.Is(err, envloped.ErrValidation) {
        log.Fatal("Invalid request:", err)
    }

    // Rate limit with usage details
    if errors.Is(err, envloped.ErrRateLimited) {
        var rle *envloped.RateLimitError
        if errors.As(err, &rle) {
            fmt.Printf("Rate limited: %s\n", rle.Reason)
            if rle.Usage != nil {
                fmt.Printf("Monthly: %d/%d\n", rle.Usage.MonthlyCount, rle.Usage.MonthlyLimit)
            }
        }
    }

    // Generic API error with status code
    var apiErr *envloped.APIError
    if errors.As(err, &apiErr) {
        fmt.Printf("API error %d: %s\n", apiErr.StatusCode, apiErr.Message)
    }
}

Error types:

Type HTTP Status Sentinel Description
*ValidationError 400 ErrValidation Invalid request fields
*APIError 401 ErrUnauthorized Missing or invalid API key
*APIError 403 ErrForbidden Domain not registered/verified
*RateLimitError 429 ErrRateLimited Usage limits exceeded
*APIError 500 -- Server error

Mocking in Tests

The EmailsSvc interface makes it easy to mock the SDK in your tests:

type mockEmailsSvc struct{}

func (m *mockEmailsSvc) Send(params *envloped.SendEmailRequest) (*envloped.SendEmailResponse, error) {
    return &envloped.SendEmailResponse{Success: true, MessageId: "mock_123"}, nil
}

func (m *mockEmailsSvc) SendWithContext(ctx context.Context, params *envloped.SendEmailRequest) (*envloped.SendEmailResponse, error) {
    return m.Send(params)
}

Version

fmt.Println(envloped.Version()) // "1.0.0"

License

MIT -- see LICENSE.

Documentation

Overview

Package envloped provides a Go client for the Envloped email API.

Usage:

client := envloped.NewClient("ev_your_api_key")
resp, err := client.Emails.Send(&envloped.SendEmailRequest{
    From:    "hello@yourdomain.com",
    To:      []string{"user@example.com"},
    Subject: "Hello from Envloped",
    Html:    "<p>Welcome!</p>",
})

Package envloped provides a Go client for the Envloped email API.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthorized is returned when the API key is missing or invalid (HTTP 401).
	ErrUnauthorized = errors.New("unauthorized")

	// ErrForbidden is returned when the request is not allowed (HTTP 403).
	// This typically means the domain is not registered or not verified.
	ErrForbidden = errors.New("forbidden")

	// ErrRateLimited is returned when usage limits have been exceeded (HTTP 429).
	ErrRateLimited = errors.New("rate limit exceeded")

	// ErrValidation is returned when the request body is invalid (HTTP 400).
	ErrValidation = errors.New("validation error")
)

Sentinel errors for use with errors.Is().

Functions

func Version

func Version() string

Version returns the SDK version string.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status code returned by the API.
	StatusCode int `json:"statusCode"`

	// Message is the primary error message.
	Message string `json:"error"`

	// Details provides additional context about the error (present on 500 responses).
	Details string `json:"details,omitempty"`
}

APIError represents a generic error response from the Envloped API.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is enables sentinel error matching via errors.Is().

type Client

type Client struct {

	// Emails provides access to the email sending API.
	Emails EmailsSvc
	// contains filtered or unexported fields
}

Client handles communication with the Envloped API.

func NewClient

func NewClient(apiKey string) *Client

NewClient creates a new Envloped API client with the given API key. The client defaults to the production API at https://api.envloped.com.

func (*Client) Ping

func (c *Client) Ping() (*PingResponse, error)

Ping checks connectivity and API key validity. Returns a PingResponse on success or an error on failure.

func (*Client) PingWithContext

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

PingWithContext checks connectivity and API key validity using the given context.

func (*Client) WithBaseURL

func (c *Client) WithBaseURL(rawURL string) *Client

WithBaseURL sets a custom base URL for the API client. This is useful for testing or self-hosted deployments. Returns the client for method chaining.

func (*Client) WithHTTPClient

func (c *Client) WithHTTPClient(httpClient *http.Client) *Client

WithHTTPClient sets a custom HTTP client for the API client. This is useful for configuring timeouts, transports, or proxies. Returns the client for method chaining.

type EmailUsage

type EmailUsage struct {
	DailyCount   int  `json:"dailyCount"`
	MonthlyCount int  `json:"monthlyCount"`
	DailyLimit   *int `json:"dailyLimit"` // nil means unlimited
	MonthlyLimit int  `json:"monthlyLimit"`
}

EmailUsage contains email usage counters and limits returned with rate limit errors.

type EmailsSvc

type EmailsSvc interface {
	// Send sends an email with the given parameters.
	Send(params *SendEmailRequest) (*SendEmailResponse, error)

	// SendWithContext sends an email using the provided context for cancellation and deadlines.
	SendWithContext(ctx context.Context, params *SendEmailRequest) (*SendEmailResponse, error)
}

EmailsSvc defines the interface for the email sending service. This interface can be mocked in consumer tests.

type PingResponse

type PingResponse struct {
	Message   string `json:"message"`
	CompanyID string `json:"companyId"`
}

PingResponse is the response from the Ping endpoint.

type RateLimitError

type RateLimitError struct {
	APIError

	// Reason is a human-readable explanation of which limit was exceeded.
	Reason string `json:"message,omitempty"`

	// Usage contains the current usage counters and limits.
	Usage *EmailUsage `json:"usage,omitempty"`
}

RateLimitError is returned when the API responds with HTTP 429. It embeds APIError and adds usage details.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

Error implements the error interface.

func (*RateLimitError) Is

func (e *RateLimitError) Is(target error) bool

Is enables sentinel error matching via errors.Is().

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the underlying APIError for errors.Unwrap() support.

type SendEmailRequest

type SendEmailRequest struct {
	// From is the sender email address (e.g., "hello@yourdomain.com" or "My App <hello@yourdomain.com>").
	// The domain must be verified in your Envloped dashboard.
	From string `json:"from"`

	// To is the list of recipient email addresses.
	To []string `json:"to"`

	// Subject is the email subject line.
	Subject string `json:"subject"`

	// Html is the HTML body of the email. At least one of Html or Text must be provided.
	Html string `json:"html,omitempty"`

	// Text is the plain text body of the email. At least one of Html or Text must be provided.
	Text string `json:"text,omitempty"`
}

SendEmailRequest is the request body for sending an email.

See https://docs.envloped.com/api-reference/emails/send-email

type SendEmailResponse

type SendEmailResponse struct {
	// Success indicates whether the email was sent successfully.
	Success bool `json:"success"`

	// MessageId is the unique identifier for the sent email (SES Message ID).
	MessageId string `json:"messageId"`
}

SendEmailResponse is the response from a successful email send.

type ValidationError

type ValidationError struct {
	APIError
}

ValidationError is returned when the API responds with HTTP 400. It embeds APIError for consistency.

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is enables sentinel error matching via errors.Is().

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying APIError for errors.Unwrap() support.

Jump to

Keyboard shortcuts

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