dashamail

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 12 Imported by: 0

README

dashamail-go

Go Reference

Go client library for the DashaMail transactional email API.

Документация на русском

Features

  • Sending transactional emails with HTML, plain text, attachments, and inline images
  • Template tag substitution (replace)
  • Delivery status checking
  • Event logs and statistics
  • Transactional webhook management
  • Functional options for client configuration
  • Per-message overrides for sender, tracking, and delivery policy
  • Typed API errors with errors.As support

Installation

go get github.com/kra-so/dashamail-go

Requires Go 1.21 or later.

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	dashamail "github.com/kra-so/dashamail-go"
)

func main() {
	client := dashamail.New("your-api-key",
		dashamail.WithFromEmail("noreply@example.com"),
		dashamail.WithFromName("My App"),
	)

	resp, err := client.Send(context.Background(), &dashamail.Message{
		To:      "user@example.com",
		Subject: "Welcome!",
		HTML:    "<h1>Hello!</h1><p>Welcome to our service.</p>",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Transaction ID:", resp.TransactionID)
}

Client Configuration

client := dashamail.New("api-key",
	dashamail.WithEndpoint("https://api.dashamail.com"),  // default
	dashamail.WithFromEmail("noreply@example.com"),       // sender email
	dashamail.WithFromName("My App"),                     // sender display name
	dashamail.WithNoTrackOpens(true),                     // disable open tracking (default: true)
	dashamail.WithNoTrackClicks(true),                    // disable click tracking (default: true)
	dashamail.WithIgnoreDeliveryPolicy(false),            // ignore delivery policy (default: false)
	dashamail.WithHTTPClient(customHTTPClient),           // custom *http.Client
	dashamail.WithDebug(true),                            // enable debug mode
)

Sending Emails

Simple Email
resp, err := client.Send(ctx, &dashamail.Message{
	To:      "user@example.com",
	Subject: "Email subject",
	HTML:    "<p>HTML content</p>",
})
With Template Substitution
resp, err := client.Send(ctx, &dashamail.Message{
	To:      "user@example.com",
	Subject: "Your order",
	HTML:    "<p>Hello, %NAME%! Your order #%ORDER% has been received.</p>",
	Replace: map[string]string{
		"%NAME%":  "John",
		"%ORDER%": "12345",
	},
})
With Attachments
msg := &dashamail.Message{
	To:      "user@example.com",
	Subject: "Report",
	HTML:    `<p>Report attached.</p><img src="cid:logo">`,
}

// File attachment
if err := msg.AttachFile("./report.pdf"); err != nil {
	log.Fatal(err)
}

// Inline image (referenced via cid: in HTML)
if err := msg.AttachInlineFile("./logo.png", "logo"); err != nil {
	log.Fatal(err)
}

resp, err := client.Send(ctx, msg)
Per-Message Overrides

Any client-level default can be overridden on an individual message:

resp, err := client.Send(ctx, &dashamail.Message{
	To:           "user@example.com",
	Subject:      "Urgent",
	HTML:         "<p>Time-sensitive email</p>",
	FromEmail:    "urgent@example.com",
	FromName:     "Urgent Bot",
	NoTrackOpens: dashamail.Bool(false), // enable open tracking for this message
})

Checking Delivery Status

status, err := client.Check(ctx, "5a802b10ba82eccfd164f3c8be0fb678")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Status: %s (%d)\n", status.StatusName, status.Status)
fmt.Printf("Sent at: %s\n", status.DateSent)

Event Logs

entries, err := client.GetLog(ctx, &dashamail.GetLogParams{
	EventType: "delivered",
	From:      "2024-01-01 00:00:00",
	To:        "2024-01-31 23:59:59",
	Limit:     100,
})

Statistics

data, err := client.GetStat(ctx, &dashamail.GetStatParams{
	Period:    "custom",
	StartDate: "2024-01-01",
	EndDate:   "2024-01-31",
})

Webhooks

// Set webhook URLs
err := client.SetTransactionalWebhooks(ctx, &dashamail.WebhookURLs{
	Open:  "https://example.com/webhooks/open",
	Click: "https://example.com/webhooks/click",
	Hard:  "https://example.com/webhooks/bounce",
})

// Get current webhooks
data, err := client.GetTransactionalWebhooks(ctx, "")

// Delete a webhook
err := client.DeleteTransactionalWebhooks(ctx, "open")

Error Handling

API errors are returned as *APIError and can be inspected using errors.As:

resp, err := client.Send(ctx, msg)
if err != nil {
	var apiErr *dashamail.APIError
	if errors.As(err, &apiErr) {
		fmt.Printf("API error %d: %s\n", apiErr.Code, apiErr.Message)
	} else {
		fmt.Printf("Error: %v\n", err)
	}
}

Message Fields Reference

Field Type Description
To string Recipient email (required)
Subject string Email subject
HTML string HTML body
PlainText string Plain-text fallback body
FromEmail string Sender email override
FromName string Sender name override
CC string Carbon copy recipient(s)
BCC string Blind carbon copy recipient(s)
MessageID string Custom Message-ID header
DeliveryTime string Scheduled delivery time (YYYY-MM-DD HH:MM:SS)
Replace map[string]string Template tag substitutions
Domain string Sending domain override
Headers map[string]string Custom email headers
TemplateData map[string]any Data for template engine
NoTrackOpens *bool Open tracking override
NoTrackClicks *bool Click tracking override
IgnoreDeliveryPolicy *bool Delivery policy override
Attachments []Attachment File attachments
Inline []InlineAttachment Inline images

Testing

go test ./...

License

MIT

Documentation

Overview

Package dashamail provides a Go client for the DashaMail transactional email API.

Usage:

client := dashamail.New("your-api-key",
	dashamail.WithFromEmail("noreply@example.com"),
	dashamail.WithFromName("My App"),
)

resp, err := client.Send(ctx, &dashamail.Message{
	To:      "user@example.com",
	Subject: "Hello",
	HTML:    "<h1>Hi!</h1>",
})

Package dashamail provides a Go client for the DashaMail transactional email API (https://dashamail.ru/transactional/).

Quick Start

Create a client and send a transactional email:

client := dashamail.New("your-api-key",
	dashamail.WithFromEmail("noreply@example.com"),
	dashamail.WithFromName("My App"),
)

resp, err := client.Send(ctx, &dashamail.Message{
	To:      "user@example.com",
	Subject: "Welcome!",
	HTML:    "<h1>Hello!</h1>",
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Transaction ID:", resp.TransactionID)

Configuration

The client is configured via functional options passed to New:

Per-message overrides are available via Message fields. Use Bool helper to set optional boolean fields.

Transactional API

The following transactional API methods are supported:

  • Client.Send — send a transactional email (transactional.send)
  • Client.Check — check delivery status (transactional.check)
  • Client.GetLog — retrieve event logs (transactional.get_log)
  • Client.GetStat — retrieve statistics (transactional.get_stat)

Webhooks

Attachments

Use Message.AttachFile and Message.AttachInlineFile to add attachments from disk:

msg := &dashamail.Message{To: "user@example.com", Subject: "Report"}
msg.AttachFile("report.pdf")
msg.AttachInlineFile("logo.png", "logo-cid")

Error Handling

API errors are returned as *APIError and can be inspected with errors.As:

var apiErr *dashamail.APIError
if errors.As(err, &apiErr) {
	fmt.Printf("API error %d: %s\n", apiErr.Code, apiErr.Message)
}

---

Пакет dashamail — Go-клиент для транзакционного email API DashaMail (https://dashamail.ru/transactional/).

Быстрый старт

Создайте клиент и отправьте транзакционное письмо:

client := dashamail.New("ваш-api-ключ",
	dashamail.WithFromEmail("noreply@example.com"),
	dashamail.WithFromName("Моё приложение"),
)

resp, err := client.Send(ctx, &dashamail.Message{
	To:      "user@example.com",
	Subject: "Добро пожаловать!",
	HTML:    "<h1>Привет!</h1>",
})

Конфигурация

Клиент настраивается через функциональные опции, передаваемые в New. Каждое сообщение может переопределить настройки клиента через поля Message. Используйте хелпер Bool для optional-булевых полей.

Транзакционное API

  • Client.Send — отправка письма (transactional.send)
  • Client.Check — проверка статуса доставки (transactional.check)
  • Client.GetLog — получение логов событий (transactional.get_log)
  • Client.GetStat — получение статистики (transactional.get_stat)

Вебхуки

Обработка ошибок

Ошибки API возвращаются как *APIError. Проверяйте через errors.As.

Index

Constants

View Source
const (
	// DefaultEndpoint is the default DashaMail API base URL.
	DefaultEndpoint = "https://api.dashamail.com"

	// Version is the library version.
	Version = "0.1.0"
)

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the given bool value. Useful for setting optional boolean fields on Message.

msg.NoTrackOpens = dashamail.Bool(false)

Types

type APIError

type APIError struct {
	Code    int
	Message string
}

APIError is returned when the DashaMail API responds with a non-zero error code.

func (*APIError) Error

func (e *APIError) Error() string

type Attachment

type Attachment struct {
	// Name is the filename as it will appear to the recipient.
	Name string `json:"name"`

	// FileBody is the Base64-encoded file content.
	FileBody string `json:"filebody"`
}

Attachment represents a file attached to an email.

type CheckResponse

type CheckResponse struct {
	Date             string `json:"date"`
	DateSent         string `json:"datesent"`
	To               string `json:"to"`
	Status           int    `json:"status"`
	StatusName       string `json:"statusname"`
	StatusChangeDate string `json:"statuschangedate"`
}

CheckResponse is returned by Client.Check.

type Client

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

Client is the DashaMail API client.

func New

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

New creates a new DashaMail client with the given API key and options.

func (*Client) Check

func (c *Client) Check(ctx context.Context, transactionID string) (*CheckResponse, error)

Check returns the delivery status of a previously sent transactional email.

func (*Client) DeleteTransactionalWebhooks

func (c *Client) DeleteTransactionalWebhooks(ctx context.Context, eventName string) error

DeleteTransactionalWebhooks deletes a transactional webhook by event name.

Event names: "open", "click", "hard", "soft", "spam", "unsub", "subscribe", "confirm".

func (*Client) GetLog

func (c *Client) GetLog(ctx context.Context, params *GetLogParams) ([]json.RawMessage, error)

GetLog returns transactional email event logs.

func (*Client) GetStat

func (c *Client) GetStat(ctx context.Context, params *GetStatParams) (json.RawMessage, error)

GetStat returns transactional email statistics for a time period.

func (*Client) GetTransactionalWebhooks

func (c *Client) GetTransactionalWebhooks(ctx context.Context, eventName string) (json.RawMessage, error)

GetTransactionalWebhooks returns the currently configured transactional webhook URLs.

If eventName is not empty, only the specified event webhook is returned.

func (*Client) Send

func (c *Client) Send(ctx context.Context, msg *Message) (*SendResponse, error)

Send sends a transactional email.

On success it returns the transaction ID which can be used with Check.

func (*Client) SetTransactionalWebhooks

func (c *Client) SetTransactionalWebhooks(ctx context.Context, urls *WebhookURLs) error

SetTransactionalWebhooks sets the transactional webhook URLs.

Pass only the event URLs you want to configure; empty strings are omitted.

type GetLogParams

type GetLogParams struct {
	// EventType filters by event type (e.g. "delivered", "opened", "clicked", "bounced", "spam").
	EventType string `json:"event_type,omitempty"`

	// Emails filters by recipient emails.
	Emails []string `json:"emails,omitempty"`

	// Sort specifies the sort order ("asc" or "desc").
	Sort string `json:"sort,omitempty"`

	// CampaignID filters by campaign.
	CampaignID string `json:"campaign_id,omitempty"`

	// Start is the offset for pagination.
	Start int `json:"start,omitempty"`

	// Limit is the maximum number of entries to return.
	Limit int `json:"limit,omitempty"`

	// From filters events from this time (format: "YYYY-MM-DD HH:MM:SS").
	From string `json:"from,omitempty"`

	// To filters events until this time (format: "YYYY-MM-DD HH:MM:SS").
	To string `json:"to,omitempty"`
}

GetLogParams configures the transactional.get_log request.

type GetLogResponse

type GetLogResponse struct {
	Entries []LogEntry
}

GetLogResponse is returned by Client.GetLog.

type GetStatParams

type GetStatParams struct {
	// Period is the statistics period: "today", "yesterday", "last_7_days",
	// "last_30_days", "last_90_days", "custom".
	Period string `json:"period,omitempty"`

	// StartDate is used with Period="custom" (format: "YYYY-MM-DD").
	StartDate string `json:"start_date,omitempty"`

	// EndDate is used with Period="custom" (format: "YYYY-MM-DD").
	EndDate string `json:"end_date,omitempty"`
}

GetStatParams configures the transactional.get_stat request.

type InlineAttachment

type InlineAttachment struct {
	// MIMEType is the MIME type of the file (e.g. "image/png").
	MIMEType string `json:"mime_type"`

	// Filename is the original filename.
	Filename string `json:"filename"`

	// Body is the Base64-encoded file content.
	Body string `json:"body"`

	// CID is the Content-ID used to reference the image in HTML (e.g. <img src="cid:123">).
	CID string `json:"cid"`
}

InlineAttachment represents an inline image in an email.

type LogEntry

type LogEntry struct {
	Date          string `json:"date"`
	Email         string `json:"email"`
	Subject       string `json:"subject"`
	Event         string `json:"event"`
	TransactionID string `json:"transaction_id"`
}

LogEntry represents a single entry from transactional.get_log.

type Message

type Message struct {
	// To is the recipient email address (required).
	To string `json:"to"`

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

	// HTML is the HTML body of the email.
	HTML string `json:"message,omitempty"`

	// PlainText is the plain-text fallback body.
	PlainText string `json:"plain_text,omitempty"`

	// FromEmail overrides the client-level sender address.
	FromEmail string `json:"from_email,omitempty"`

	// FromName overrides the client-level sender name.
	FromName string `json:"from_name,omitempty"`

	// CC is the carbon copy recipient(s).
	CC string `json:"cc,omitempty"`

	// BCC is the blind carbon copy recipient(s).
	BCC string `json:"bcc,omitempty"`

	// MessageID is a custom Message-ID header value.
	MessageID string `json:"message_id,omitempty"`

	// DeliveryTime schedules the email for a specific time (format: "YYYY-MM-DD HH:MM:SS").
	DeliveryTime string `json:"delivery_time,omitempty"`

	// Replace is a map of template tags to replacement values.
	// For example: {"%TAG1%": "value1", "%TAG2%": "value2"}
	Replace map[string]string `json:"replace,omitempty"`

	// Domain overrides the sending domain.
	Domain string `json:"domain,omitempty"`

	// Headers is a map of custom email headers.
	Headers map[string]string `json:"headers,omitempty"`

	// TemplateData is arbitrary data passed to the template engine.
	TemplateData map[string]any `json:"template_data,omitempty"`

	// NoTrackOpens overrides the client-level open tracking setting.
	// nil means use the client default.
	NoTrackOpens *bool `json:"no_track_opens,omitempty"`

	// NoTrackClicks overrides the client-level click tracking setting.
	// nil means use the client default.
	NoTrackClicks *bool `json:"no_track_clicks,omitempty"`

	// IgnoreDeliveryPolicy overrides the client-level delivery policy setting.
	// nil means use the client default.
	IgnoreDeliveryPolicy *bool `json:"ignore_delivery_policy,omitempty"`

	// Attachments is a list of file attachments.
	Attachments []Attachment `json:"attachments,omitempty"`

	// Inline is a list of inline images (referenced via cid: in HTML).
	Inline []InlineAttachment `json:"inline,omitempty"`
}

Message describes an email to be sent via the transactional API.

func (*Message) AttachFile

func (m *Message) AttachFile(path string) error

AttachFile reads a file from disk and appends it to msg.Attachments.

func (*Message) AttachInlineFile

func (m *Message) AttachInlineFile(path, cid string) error

AttachInlineFile reads a file from disk and appends it to msg.Inline with the given CID.

type Option

type Option func(*Client)

Option configures the Client.

func WithDebug

func WithDebug(v bool) Option

WithDebug enables debug logging to stderr.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint sets a custom API endpoint.

func WithFromEmail

func WithFromEmail(email string) Option

WithFromEmail sets the default sender email address.

func WithFromName

func WithFromName(name string) Option

WithFromName sets the default sender display name.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a custom *http.Client for requests.

func WithIgnoreDeliveryPolicy

func WithIgnoreDeliveryPolicy(v bool) Option

WithIgnoreDeliveryPolicy sets whether to ignore the delivery policy.

func WithNoTrackClicks

func WithNoTrackClicks(v bool) Option

WithNoTrackClicks disables or enables click tracking (default: disabled).

func WithNoTrackOpens

func WithNoTrackOpens(v bool) Option

WithNoTrackOpens disables or enables open tracking (default: disabled).

type RawResponse

type RawResponse struct {
	// HTTPCode is the HTTP status code.
	HTTPCode int

	// Body is the raw response body bytes.
	Body []byte

	// Msg contains the API-level status message.
	Msg ResponseMsg

	// Data is the raw JSON of the "data" field in the response.
	Data json.RawMessage
}

RawResponse holds the raw API response data.

type ResponseMsg

type ResponseMsg struct {
	ErrCode int    `json:"err_code"`
	Text    string `json:"text"`
	Type    string `json:"type"`
}

ResponseMsg represents the "msg" object in every DashaMail API response.

type SendResponse

type SendResponse struct {
	TransactionID string `json:"transaction_id"`
}

SendResponse is returned by Client.Send.

type StatEntry

type StatEntry struct {
	Date      string `json:"date"`
	Sent      int    `json:"sent"`
	Delivered int    `json:"delivered"`
	Opened    int    `json:"opened"`
	Clicked   int    `json:"clicked"`
	Bounced   int    `json:"bounced"`
	Spam      int    `json:"spam"`
	Unsub     int    `json:"unsub"`
}

StatEntry represents a statistics record from transactional.get_stat.

type WebhookURLs

type WebhookURLs struct {
	Open      string `json:"open,omitempty"`
	Click     string `json:"click,omitempty"`
	Hard      string `json:"hard,omitempty"`
	Soft      string `json:"soft,omitempty"`
	Spam      string `json:"spam,omitempty"`
	Unsub     string `json:"unsub,omitempty"`
	Subscribe string `json:"subscribe,omitempty"`
	Confirm   string `json:"confirm,omitempty"`
}

WebhookURLs holds the current transactional webhook URLs.

Jump to

Keyboard shortcuts

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