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:
- WithEndpoint — custom API base URL (default: https://api.dashamail.com)
- WithFromEmail — default sender email address
- WithFromName — default sender display name
- WithNoTrackOpens — disable open tracking (default: true)
- WithNoTrackClicks — disable click tracking (default: true)
- WithIgnoreDeliveryPolicy — ignore delivery policy (default: false)
- WithHTTPClient — custom *http.Client
- WithDebug — enable debug mode
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 ¶
- Client.GetTransactionalWebhooks — get configured webhook URLs
- Client.SetTransactionalWebhooks — set webhook URLs
- Client.DeleteTransactionalWebhooks — remove a webhook
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)
Вебхуки ¶
- Client.GetTransactionalWebhooks — получить URL-ы вебхуков
- Client.SetTransactionalWebhooks — установить вебхуки
- Client.DeleteTransactionalWebhooks — удалить вебхук
Обработка ошибок ¶
Ошибки API возвращаются как *APIError. Проверяйте через errors.As.
Index ¶
- Constants
- func Bool(v bool) *bool
- type APIError
- type Attachment
- type CheckResponse
- type Client
- func (c *Client) Check(ctx context.Context, transactionID string) (*CheckResponse, error)
- func (c *Client) DeleteTransactionalWebhooks(ctx context.Context, eventName string) error
- func (c *Client) GetLog(ctx context.Context, params *GetLogParams) ([]json.RawMessage, error)
- func (c *Client) GetStat(ctx context.Context, params *GetStatParams) (json.RawMessage, error)
- func (c *Client) GetTransactionalWebhooks(ctx context.Context, eventName string) (json.RawMessage, error)
- func (c *Client) Send(ctx context.Context, msg *Message) (*SendResponse, error)
- func (c *Client) SetTransactionalWebhooks(ctx context.Context, urls *WebhookURLs) error
- type GetLogParams
- type GetLogResponse
- type GetStatParams
- type InlineAttachment
- type LogEntry
- type Message
- type Option
- func WithDebug(v bool) Option
- func WithEndpoint(endpoint string) Option
- func WithFromEmail(email string) Option
- func WithFromName(name string) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithIgnoreDeliveryPolicy(v bool) Option
- func WithNoTrackClicks(v bool) Option
- func WithNoTrackOpens(v bool) Option
- type RawResponse
- type ResponseMsg
- type SendResponse
- type StatEntry
- type WebhookURLs
Constants ¶
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 ¶
Types ¶
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 (*Client) DeleteTransactionalWebhooks ¶
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 ¶
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 ¶
AttachFile reads a file from disk and appends it to msg.Attachments.
func (*Message) AttachInlineFile ¶
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 WithEndpoint ¶
WithEndpoint sets a custom API endpoint.
func WithFromEmail ¶
WithFromEmail sets the default sender email address.
func WithFromName ¶
WithFromName sets the default sender display name.
func WithHTTPClient ¶
WithHTTPClient sets a custom *http.Client for requests.
func WithIgnoreDeliveryPolicy ¶
WithIgnoreDeliveryPolicy sets whether to ignore the delivery policy.
func WithNoTrackClicks ¶
WithNoTrackClicks disables or enables click tracking (default: disabled).
func WithNoTrackOpens ¶
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.