Documentation
¶
Overview ¶
Package haskimail — Go-клиент для API Haskimail (https://api.haskimail.ru/), сервиса транзакционной электронной почты.
Пакет предоставляет два клиента:
- Client — серверный API (отправка писем, шаблоны, отказы, статистика, вебхуки, каналы, стоп-списки). Создаётся через NewClient с серверным токеном.
- AccountClient — API аккаунта (серверы, домены, подписи отправителей, пуш шаблонов). Создаётся через NewAccountClient с токеном аккаунта.
Пример:
client := haskimail.NewClient("ваш-серверный-токен")
resp, err := client.DeliverMessage(ctx, &haskimail.Message{
From: "отправитель@домен.ru",
To: "получатель@домен.ru",
Subject: "Тема письма",
HTMLBody: "<h1>Привет!</h1>",
})
Все методы принимают context.Context для отмены и таймаутов. Ошибки API возвращаются как *Error и проверяются через errors.Is / errors.As:
if errors.Is(err, haskimail.ErrInvalidAPIKey) { ... }
Пакет не имеет внешних зависимостей — только стандартная библиотека.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/DashaMail/haskimail-go"
)
func main() {
client := haskimail.NewClient("ваш-серверный-токен")
msg := &haskimail.Message{
From: "отправитель@домен.ru",
To: "получатель@домен.ru",
Subject: "Тема письма",
HTMLBody: "<h1>Привет!</h1><p>Это письмо отправлено через Haskimail.</p>",
TrackOpens: haskimail.Bool(true),
TrackLinks: haskimail.TrackLinksHTMLAndText,
}
msg.AddMetadata("campaign", "welcome")
resp, err := client.DeliverMessage(context.Background(), msg)
if errors.Is(err, haskimail.ErrInvalidMessage) {
var apiErr *haskimail.Error
errors.As(err, &apiErr)
log.Fatalf("письмо отклонено: код %d, %s", apiErr.ErrorCode, apiErr.Message)
} else if err != nil {
log.Fatal(err)
}
fmt.Println("ID сообщения:", resp.MessageID)
}
Output:
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func FormatRecipients(rs ...Recipient) string
- func FormatRecipientsMap(m map[string]string) string
- func Int(v int) *int
- func ParseTime(s string) (time.Time, error)
- func String(v string) *string
- type AccountClient
- func (b AccountClient) BaseURL() string
- func (c *AccountClient) CreateDomain(ctx context.Context, d *Domain) (*DomainDetails, error)
- func (c *AccountClient) CreateServer(ctx context.Context, s *Server) (*Server, error)
- func (c *AccountClient) DeleteDomain(ctx context.Context, id int64) (*RequestResponse, error)
- func (c *AccountClient) DeleteServer(ctx context.Context, id int64) (*RequestResponse, error)
- func (c *AccountClient) GetDomainDetails(ctx context.Context, id int64) (*DomainDetails, error)
- func (c *AccountClient) GetDomains(ctx context.Context) (*Domains, error)
- func (c *AccountClient) GetServer(ctx context.Context, id int64) (*Server, error)
- func (c *AccountClient) GetServers(ctx context.Context, p *Params) (*Servers, error)
- func (c *AccountClient) PushTemplates(ctx context.Context, r *TemplatesPushRequest) (*TemplatesPush, error)
- func (c *AccountClient) SetServer(ctx context.Context, id int64, s *Server) (*Server, error)
- func (c *AccountClient) VerifyDomainDKIM(ctx context.Context, id int64) (*DomainDetails, error)
- func (c *AccountClient) VerifyDomainSPF(ctx context.Context, id int64) (*DomainDetails, error)
- type Attachment
- type BaseTemplate
- type Bounce
- type BounceStat
- type BounceType
- type BounceWebhook
- type BounceWebhookTrigger
- type Bounces
- type ClickStat
- type ClickWebhook
- type Client
- func (c *Client) ArchiveMessageStream(ctx context.Context, id string) (*MessageStreamArchiveResponse, error)
- func (b Client) BaseURL() string
- func (c *Client) CreateMessageStream(ctx context.Context, s *MessageStream) (*MessageStream, error)
- func (c *Client) CreateSuppressions(ctx context.Context, messageStream string, e SuppressionEntries) (*SuppressionStatuses, error)
- func (c *Client) CreateTemplate(ctx context.Context, t *Template) (*Template, error)
- func (c *Client) CreateWebhook(ctx context.Context, w *Webhook) (*Webhook, error)
- func (c *Client) DeleteSuppressions(ctx context.Context, messageStream string, e SuppressionEntries) (*SuppressionStatuses, error)
- func (c *Client) DeleteTemplate(ctx context.Context, id int64) (*RequestResponse, error)
- func (c *Client) DeleteTemplateByAlias(ctx context.Context, alias string) (*RequestResponse, error)
- func (c *Client) DeleteWebhook(ctx context.Context, id int64) (*RequestResponse, error)
- func (c *Client) DeliverMessage(ctx context.Context, m *Message) (*MessageResponse, error)
- func (c *Client) DeliverMessageWithTemplate(ctx context.Context, m *TemplatedMessage) (*MessageResponse, error)
- func (c *Client) DeliverMessages(ctx context.Context, ms []Message) ([]MessageResponse, error)
- func (c *Client) DeliverMessagesWithTemplate(ctx context.Context, ms []TemplatedMessage) ([]MessageResponse, error)
- func (c *Client) GetBounceStats(ctx context.Context, p *Params) (*OutboundBounceStats, error)
- func (c *Client) GetBounces(ctx context.Context, p *Params) (*Bounces, error)
- func (c *Client) GetClickBrowserStats(ctx context.Context, p *Params) (*OutboundClickBrowserStats, error)
- func (c *Client) GetClickPlatformStats(ctx context.Context, p *Params) (*OutboundClickPlatformStats, error)
- func (c *Client) GetClickStats(ctx context.Context, p *Params) (*OutboundClickStats, error)
- func (c *Client) GetDeliveryStats(ctx context.Context) (*DeliveryStats, error)
- func (c *Client) GetMessageClicks(ctx context.Context, p *Params) (*OutboundMessageClicks, error)
- func (c *Client) GetMessageClicksByID(ctx context.Context, messageID string, p *Params) (*OutboundMessageClicks, error)
- func (c *Client) GetMessageDetails(ctx context.Context, messageID string) (*OutboundMessageDetails, error)
- func (c *Client) GetMessageOpens(ctx context.Context, p *Params) (*OutboundMessageOpens, error)
- func (c *Client) GetMessageOpensByID(ctx context.Context, messageID string, p *Params) (*OutboundMessageOpens, error)
- func (c *Client) GetMessageStream(ctx context.Context, id string) (*MessageStream, error)
- func (c *Client) GetMessageStreams(ctx context.Context) (*MessageStreams, error)
- func (c *Client) GetMessages(ctx context.Context, p *Params) (*OutboundMessages, error)
- func (c *Client) GetOpenEmailClientStats(ctx context.Context, p *Params) (*OutboundOpenEmailClientStats, error)
- func (c *Client) GetOpenPlatformStats(ctx context.Context, p *Params) (*OutboundOpenPlatformStats, error)
- func (c *Client) GetOpenStats(ctx context.Context, p *Params) (*OutboundOpenStats, error)
- func (c *Client) GetOutboundStats(ctx context.Context, p *Params) (*OutboundStats, error)
- func (c *Client) GetSendStats(ctx context.Context, p *Params) (*OutboundSendStats, error)
- func (c *Client) GetSpamStats(ctx context.Context, p *Params) (*OutboundSpamStats, error)
- func (c *Client) GetSuppressions(ctx context.Context, messageStream string, p *Params) (*Suppressions, error)
- func (c *Client) GetTemplate(ctx context.Context, id int64) (*Template, error)
- func (c *Client) GetTemplateByAlias(ctx context.Context, alias string) (*Template, error)
- func (c *Client) GetTemplates(ctx context.Context, p *Params) (*Templates, error)
- func (c *Client) GetWebhook(ctx context.Context, id int64) (*Webhook, error)
- func (c *Client) GetWebhooks(ctx context.Context, p *Params) (*Webhooks, error)
- func (c *Client) SetMessageStream(ctx context.Context, id string, s *MessageStream) (*MessageStream, error)
- func (c *Client) SetTemplate(ctx context.Context, id int64, t *Template) (*Template, error)
- func (c *Client) SetTemplateByAlias(ctx context.Context, alias string, t *Template) (*Template, error)
- func (c *Client) SetWebhook(ctx context.Context, id int64, w *Webhook) (*Webhook, error)
- func (c *Client) UnarchiveMessageStream(ctx context.Context, id string) (*MessageStreamUnarchiveResponse, error)
- func (c *Client) ValidateTemplate(ctx context.Context, t *TemplateToValidate) (*TemplateValidation, error)
- type DNSRecord
- type DayStats
- type DeliveryStats
- type DeliveryWebhook
- type Domain
- type DomainDetails
- type Domains
- type Error
- type HTTPAuth
- type Header
- type Message
- type MessageResponse
- type MessageStream
- type MessageStreamArchiveResponse
- type MessageStreamUnarchiveResponse
- type MessageStreams
- type NamedCountStat
- type NamedCountStats
- type OpenStat
- type OpenWebhook
- type OpenWebhookTrigger
- type Option
- func WithBaseURL(host string) Option
- func WithConnectTimeout(d time.Duration) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithHeader(name, value string) Option
- func WithInsecure() Option
- func WithReadTimeout(d time.Duration) Option
- func WithSecureConnection(secure bool) Option
- func WithUserAgent(ua string) Option
- type OutboundBounceStats
- type OutboundClickBrowserStats
- type OutboundClickPlatformStats
- type OutboundClickStats
- type OutboundMessage
- type OutboundMessageClick
- type OutboundMessageClicks
- type OutboundMessageDetails
- type OutboundMessageDetailsEvent
- type OutboundMessageOpen
- type OutboundMessageOpens
- type OutboundMessages
- type OutboundOpenEmailClientStats
- type OutboundOpenPlatformStats
- type OutboundOpenStats
- type OutboundSendStats
- type OutboundSpamStats
- type OutboundStats
- type Params
- type PlatformStat
- type PlatformStats
- type Recipient
- type RequestResponse
- type SentStat
- type Server
- type Servers
- type SpamStat
- type SpamWebhookTrigger
- type SubscriptionChange
- type SubscriptionManagementConfiguration
- type Suppression
- type SuppressionEntries
- type SuppressionEntry
- type SuppressionStatus
- type SuppressionStatuses
- type Suppressions
- type Template
- type TemplateContent
- type TemplateToValidate
- type TemplateValidation
- type TemplateValidationError
- type TemplateValidationField
- type TemplatedMessage
- type Templates
- type TemplatesPush
- type TemplatesPushAction
- type TemplatesPushRequest
- type Time
- type Webhook
- type WebhookTrigger
- type WebhookTriggers
- type Webhooks
Examples ¶
Constants ¶
const ( // Version — версия библиотеки. Version = "1.3.0" // DefaultAPIURL — хост API по умолчанию. DefaultAPIURL = "api.haskimail.ru" // ServerTokenHeader — заголовок для серверного токена. ServerTokenHeader = "X-Haski-Server-Token" // AccountTokenHeader — заголовок для токена аккаунта. AccountTokenHeader = "X-Haski-Account-Token" // DefaultConnectTimeout — таймаут установки соединения по умолчанию. DefaultConnectTimeout = 60 * time.Second // DefaultReadTimeout — таймаут ожидания ответа по умолчанию. DefaultReadTimeout = 60 * time.Second )
const ( TrackLinksNone = "None" TrackLinksHTMLAndText = "HtmlAndText" TrackLinksHTMLOnly = "HtmlOnly" TrackLinksTextOnly = "TextOnly" // Deprecated: используйте TrackLinksHTMLOnly. API принимает и это значение. TrackLinksHTML = "Html" // Deprecated: используйте TrackLinksTextOnly. API принимает и это значение. TrackLinksText = "Text" )
Режимы отслеживания ссылок (поле TrackLinks). В письме None выключает отслеживание, любое другое значение включает его. В настройках сервера различаются все четыре: None, HtmlAndText, HtmlOnly, TextOnly.
const ( MessageStreamTransactional = "Transactional" MessageStreamBroadcasts = "Broadcasts" MessageStreamInbound = "Inbound" )
Типы каналов.
const ( TemplateTypeStandard = "Standard" TemplateTypeLayout = "Layout" )
Типы шаблонов.
Variables ¶
var ( // ErrInvalidAPIKey — HTTP 401, неверный или отсутствующий токен. ErrInvalidAPIKey = errors.New("haskimail: неверный API-токен") // ErrTimeout — HTTP 408. ErrTimeout = errors.New("haskimail: таймаут запроса") // ErrInvalidMessage — HTTP 422, ошибка валидации запроса. ErrInvalidMessage = errors.New("haskimail: некорректный запрос") // ErrInternalServer — HTTP 500. ErrInternalServer = errors.New("haskimail: внутренняя ошибка сервера") // ErrUnknown — любой другой неуспешный HTTP-статус. ErrUnknown = errors.New("haskimail: неизвестная ошибка") )
Сентинел-ошибки для проверки через errors.Is.
var TimeLocation = time.Local
TimeLocation — часовой пояс для дат API, пришедших без указания зоны (например "2024-01-02 15:04:05"). По умолчанию — локальный.
Functions ¶
func FormatRecipients ¶
FormatRecipients собирает строку адресатов вида "Имя"<email>,"Имя2"<email2> для полей To, Cc и Bcc.
func FormatRecipientsMap ¶
FormatRecipientsMap собирает строку адресатов из карты: ключ — имя, значение — email. Порядок детерминирован (сортировка по имени).
Types ¶
type AccountClient ¶
type AccountClient struct {
// contains filtered or unexported fields
}
AccountClient — клиент API аккаунта Haskimail. Безопасен для конкурентного использования.
func NewAccountClient ¶
func NewAccountClient(accountToken string, opts ...Option) *AccountClient
NewAccountClient создаёт клиент API аккаунта.
func (AccountClient) BaseURL ¶
func (b AccountClient) BaseURL() string
BaseURL возвращает базовый URL клиента, например "https://api.haskimail.ru".
func (*AccountClient) CreateDomain ¶
func (c *AccountClient) CreateDomain(ctx context.Context, d *Domain) (*DomainDetails, error)
CreateDomain добавляет домен.
func (*AccountClient) CreateServer ¶
CreateServer создаёт сервер.
func (*AccountClient) DeleteDomain ¶
func (c *AccountClient) DeleteDomain(ctx context.Context, id int64) (*RequestResponse, error)
DeleteDomain удаляет домен.
func (*AccountClient) DeleteServer ¶
func (c *AccountClient) DeleteServer(ctx context.Context, id int64) (*RequestResponse, error)
DeleteServer удаляет сервер.
func (*AccountClient) GetDomainDetails ¶
func (c *AccountClient) GetDomainDetails(ctx context.Context, id int64) (*DomainDetails, error)
GetDomainDetails возвращает подробности домена.
func (*AccountClient) GetDomains ¶
func (c *AccountClient) GetDomains(ctx context.Context) (*Domains, error)
GetDomains возвращает список доменов.
func (*AccountClient) GetServers ¶
GetServers возвращает список серверов.
func (*AccountClient) PushTemplates ¶
func (c *AccountClient) PushTemplates(ctx context.Context, r *TemplatesPushRequest) (*TemplatesPush, error)
PushTemplates копирует шаблоны между серверами.
func (*AccountClient) VerifyDomainDKIM ¶
func (c *AccountClient) VerifyDomainDKIM(ctx context.Context, id int64) (*DomainDetails, error)
VerifyDomainDKIM проверяет DKIM-запись домена.
func (*AccountClient) VerifyDomainSPF ¶
func (c *AccountClient) VerifyDomainSPF(ctx context.Context, id int64) (*DomainDetails, error)
VerifyDomainSPF проверяет SPF-запись домена.
type Attachment ¶
type Attachment struct {
Name string `json:"Name,omitempty"`
Content string `json:"Content,omitempty"`
ContentType string `json:"ContentType,omitempty"`
ContentID string `json:"ContentId,omitempty"`
ContentLength int `json:"ContentLength,omitempty"`
}
Attachment — вложение письма. Content — содержимое в Base64.
func AttachmentFromFile ¶
func AttachmentFromFile(path, contentID string) (Attachment, error)
AttachmentFromFile читает файл с диска и создаёт вложение. Тип содержимого определяется по расширению, а если не удалось — по содержимому.
func NewAttachment ¶
func NewAttachment(name string, content []byte, contentType, contentID string) Attachment
NewAttachment создаёт вложение из байтов (кодирует их в Base64). contentID задаётся для встраиваемых (inline) изображений, иначе пустая строка.
type BaseTemplate ¶
type BaseTemplate struct {
TemplateID int64 `json:"TemplateId,omitempty"`
Alias string `json:"Alias,omitempty"`
Name string `json:"Name,omitempty"`
Active *bool `json:"Active,omitempty"`
TemplateType string `json:"TemplateType,omitempty"`
LayoutTemplate string `json:"LayoutTemplate,omitempty"`
}
BaseTemplate — краткие сведения о шаблоне (в списке шаблонов).
type Bounce ¶
type Bounce struct {
ID int64 `json:"ID"`
MessageID string `json:"MessageID"`
ServerID int64 `json:"ServerID"`
Type string `json:"Type"`
// TypeCode — код причины возврата; API отдаёт его строкой.
TypeCode string `json:"TypeCode"`
BouncedAt *Time `json:"BouncedAt"`
DumpAvailable bool `json:"DumpAvailable"`
Email string `json:"Email"`
From string `json:"From"`
Subject string `json:"Subject"`
Content string `json:"Content"`
Inactive bool `json:"Inactive"`
CanActivate bool `json:"CanActivate"`
Name string `json:"Name"`
Tag string `json:"Tag"`
Description string `json:"Description"`
Details string `json:"Details"`
RecordType string `json:"RecordType"`
MessageStream string `json:"MessageStream"`
}
Bounce — отказ доставки.
type BounceStat ¶
type BounceStat struct {
Date *Time `json:"Date"`
HardBounce int `json:"HardBounce"`
SoftBounce int `json:"SoftBounce"`
SMTPAPIError int `json:"SmtpApiError"`
Transient int `json:"Transient"`
Unknown int `json:"Unknown"`
DMARCPolicy int `json:"DMARCPolicy"`
Subscribe int `json:"Subscribe"`
}
BounceStat — отказы за день по типам.
type BounceType ¶
type BounceType struct {
Type string `json:"Type"`
Name string `json:"Name"`
Count int `json:"Count"`
}
BounceType — счётчик отказов одного типа.
type BounceWebhook ¶
BounceWebhook — событие отказа.
type BounceWebhookTrigger ¶
type BounceWebhookTrigger struct {
Enabled *bool `json:"Enabled,omitempty"`
IncludeContent *bool `json:"IncludeContent,omitempty"`
}
BounceWebhookTrigger — триггер отказов и жалоб на спам.
type ClickStat ¶
type ClickStat struct {
Date *Time `json:"Date"`
Clicks int `json:"Clicks"`
Unique int `json:"Unique"`
}
ClickStat — клики за день.
type ClickWebhook ¶
type ClickWebhook struct {
OutboundMessageClick
Metadata map[string]string `json:"Metadata"`
}
ClickWebhook — событие клика.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client — клиент серверного API Haskimail. Безопасен для конкурентного использования.
func (*Client) ArchiveMessageStream ¶
func (c *Client) ArchiveMessageStream(ctx context.Context, id string) (*MessageStreamArchiveResponse, error)
ArchiveMessageStream архивирует канал.
func (Client) BaseURL ¶
func (b Client) BaseURL() string
BaseURL возвращает базовый URL клиента, например "https://api.haskimail.ru".
func (*Client) CreateMessageStream ¶
func (c *Client) CreateMessageStream(ctx context.Context, s *MessageStream) (*MessageStream, error)
CreateMessageStream создаёт канал.
func (*Client) CreateSuppressions ¶
func (c *Client) CreateSuppressions(ctx context.Context, messageStream string, e SuppressionEntries) (*SuppressionStatuses, error)
CreateSuppressions добавляет адреса в стоп-лист канала.
func (*Client) CreateTemplate ¶
CreateTemplate создаёт шаблон.
func (*Client) CreateWebhook ¶
CreateWebhook создаёт вебхук.
func (*Client) DeleteSuppressions ¶
func (c *Client) DeleteSuppressions(ctx context.Context, messageStream string, e SuppressionEntries) (*SuppressionStatuses, error)
DeleteSuppressions удаляет адреса из стоп-листа канала.
func (*Client) DeleteTemplate ¶
DeleteTemplate удаляет шаблон по ID.
func (*Client) DeleteTemplateByAlias ¶
DeleteTemplateByAlias удаляет шаблон по алиасу.
func (*Client) DeleteWebhook ¶
DeleteWebhook удаляет вебхук.
func (*Client) DeliverMessage ¶
DeliverMessage отправляет одно письмо.
func (*Client) DeliverMessageWithTemplate ¶
func (c *Client) DeliverMessageWithTemplate(ctx context.Context, m *TemplatedMessage) (*MessageResponse, error)
DeliverMessageWithTemplate отправляет письмо по шаблону.
func (*Client) DeliverMessages ¶
DeliverMessages отправляет пакет писем: до 500 писем и 50 МБ за запрос. Ошибки отдельных писем не возвращаются как error: результат каждого письма — в элементе ответа с тем же номером, проверяйте его ErrorCode.
func (*Client) DeliverMessagesWithTemplate ¶
func (c *Client) DeliverMessagesWithTemplate(ctx context.Context, ms []TemplatedMessage) ([]MessageResponse, error)
DeliverMessagesWithTemplate отправляет пакет писем по шаблонам. Ограничения и разбор ответа — как у DeliverMessages.
func (*Client) GetBounceStats ¶
GetBounceStats возвращает отказы по дням.
func (*Client) GetBounces ¶
GetBounces возвращает список отказов. Обычно требуются параметры count и offset.
func (*Client) GetClickBrowserStats ¶ added in v1.3.0
func (c *Client) GetClickBrowserStats(ctx context.Context, p *Params) (*OutboundClickBrowserStats, error)
GetClickBrowserStats возвращает клики по браузерам.
func (*Client) GetClickPlatformStats ¶
func (c *Client) GetClickPlatformStats(ctx context.Context, p *Params) (*OutboundClickPlatformStats, error)
GetClickPlatformStats возвращает клики по платформам: по дням и итог за период.
func (*Client) GetClickStats ¶
GetClickStats возвращает клики по дням.
func (*Client) GetDeliveryStats ¶
func (c *Client) GetDeliveryStats(ctx context.Context) (*DeliveryStats, error)
GetDeliveryStats возвращает сводку по доставке.
func (*Client) GetMessageClicks ¶
GetMessageClicks возвращает клики по всем сообщениям.
func (*Client) GetMessageClicksByID ¶
func (c *Client) GetMessageClicksByID(ctx context.Context, messageID string, p *Params) (*OutboundMessageClicks, error)
GetMessageClicksByID возвращает клики одного сообщения.
func (*Client) GetMessageDetails ¶
func (c *Client) GetMessageDetails(ctx context.Context, messageID string) (*OutboundMessageDetails, error)
GetMessageDetails возвращает подробности сообщения.
func (*Client) GetMessageOpens ¶
GetMessageOpens возвращает открытия по всем сообщениям.
func (*Client) GetMessageOpensByID ¶
func (c *Client) GetMessageOpensByID(ctx context.Context, messageID string, p *Params) (*OutboundMessageOpens, error)
GetMessageOpensByID возвращает открытия одного сообщения.
func (*Client) GetMessageStream ¶
GetMessageStream возвращает канал по ID.
func (*Client) GetMessageStreams ¶
func (c *Client) GetMessageStreams(ctx context.Context) (*MessageStreams, error)
GetMessageStreams возвращает каналы сервера.
func (*Client) GetMessages ¶
GetMessages ищет исходящие сообщения.
func (*Client) GetOpenEmailClientStats ¶ added in v1.3.0
func (c *Client) GetOpenEmailClientStats(ctx context.Context, p *Params) (*OutboundOpenEmailClientStats, error)
GetOpenEmailClientStats возвращает открытия по почтовым клиентам и веб-почтам.
func (*Client) GetOpenPlatformStats ¶
func (c *Client) GetOpenPlatformStats(ctx context.Context, p *Params) (*OutboundOpenPlatformStats, error)
GetOpenPlatformStats возвращает открытия по платформам: по дням и итог за период.
func (*Client) GetOpenStats ¶
GetOpenStats возвращает открытия по дням.
func (*Client) GetOutboundStats ¶
GetOutboundStats возвращает сводную статистику.
func (*Client) GetSendStats ¶
GetSendStats возвращает число отправленных писем по дням.
func (*Client) GetSpamStats ¶
GetSpamStats возвращает жалобы на спам по дням.
func (*Client) GetSuppressions ¶
func (c *Client) GetSuppressions(ctx context.Context, messageStream string, p *Params) (*Suppressions, error)
GetSuppressions возвращает стоп-лист канала.
func (*Client) GetTemplate ¶
GetTemplate возвращает шаблон по ID.
func (*Client) GetTemplateByAlias ¶
GetTemplateByAlias возвращает шаблон по алиасу.
func (*Client) GetTemplates ¶
GetTemplates возвращает список шаблонов.
func (*Client) GetWebhook ¶
GetWebhook возвращает вебхук по ID.
func (*Client) GetWebhooks ¶
GetWebhooks возвращает список вебхуков (можно фильтровать по MessageStream).
func (*Client) SetMessageStream ¶
func (c *Client) SetMessageStream(ctx context.Context, id string, s *MessageStream) (*MessageStream, error)
SetMessageStream изменяет канал (PATCH).
func (*Client) SetTemplate ¶
SetTemplate изменяет шаблон по ID.
func (*Client) SetTemplateByAlias ¶
func (c *Client) SetTemplateByAlias(ctx context.Context, alias string, t *Template) (*Template, error)
SetTemplateByAlias изменяет шаблон по алиасу.
func (*Client) SetWebhook ¶
SetWebhook изменяет вебхук.
func (*Client) UnarchiveMessageStream ¶
func (c *Client) UnarchiveMessageStream(ctx context.Context, id string) (*MessageStreamUnarchiveResponse, error)
UnarchiveMessageStream восстанавливает канал из архива.
func (*Client) ValidateTemplate ¶ added in v1.3.0
func (c *Client) ValidateTemplate(ctx context.Context, t *TemplateToValidate) (*TemplateValidation, error)
ValidateTemplate проверяет шаблон без сохранения: подставляет TestRenderModel так же, как TemplateModel при отправке, и находит фрагменты {{…}}, оставшиеся без значения. Ошибки в шаблоне не возвращаются как error — они в ответе (AllContentIsValid).
type DNSRecord ¶ added in v1.1.0
type DNSRecord struct {
// Name — имя записи с точкой на конце, например "dm._domainkey.example.com.".
Name string `json:"name"`
// RecordType — тип записи, всегда "TXT".
RecordType string `json:"record_type"`
// Value — значение записи.
Value string `json:"value"`
// Valid — 1, если запись в DNS найдена и верна.
Valid int `json:"valid"`
}
DNSRecord — DNS-запись, которую нужно добавить домену.
type DayStats ¶
type DayStats[T any] struct { Days []T `json:"Days"` }
DayStats — статистика с разбивкой по дням.
type DeliveryStats ¶
type DeliveryStats struct {
InactiveMails int `json:"InactiveMails"`
Bounces []BounceType `json:"Bounces"`
}
DeliveryStats — сводка по доставке.
type DeliveryWebhook ¶
type DeliveryWebhook struct {
ServerID int64 `json:"ServerID"`
MessageID string `json:"MessageID"`
Recipient string `json:"Recipient"`
Tag string `json:"Tag"`
DeliveredAt *Time `json:"DeliveredAt"`
Details string `json:"Details"`
RecordType string `json:"RecordType"`
Metadata map[string]string `json:"Metadata"`
MessageStream string `json:"MessageStream"`
}
DeliveryWebhook — событие доставки.
type Domain ¶
type Domain struct {
ID int64 `json:"ID,omitempty"`
Name string `json:"Name,omitempty"`
SPFVerified bool `json:"SPFVerified,omitempty"`
DKIMVerified bool `json:"DKIMVerified,omitempty"`
WeakDKIM bool `json:"WeakDKIM,omitempty"`
ReturnPathDomainVerified bool `json:"ReturnPathDomainVerified,omitempty"`
}
Domain — домен отправителя. В запросах создания/изменения значимо в основном поле Name; флаги проверки только для чтения.
type DomainDetails ¶
type DomainDetails struct {
Domain
SPFHost string `json:"SPFHost"`
SPFTextValue *DNSRecord `json:"SPFTextValue"`
DKIMHost string `json:"DKIMHost"`
DKIMTextValue *DNSRecord `json:"DKIMTextValue"`
DKIMPendingHost string `json:"DkimPendingHost"`
DKIMPendingTextValue string `json:"DkimPendingTextValue"`
DKIMRevokedHost string `json:"DkimRevokedHost"`
DKIMRevokedTextValue string `json:"DkimRevokedTextValue"`
DKIMUpdateStatus string `json:"DkimUpdateStatus"`
ReturnPathDomain string `json:"ReturnPathDomain"`
ReturnPathDomainCNAMEValue string `json:"ReturnPathDomainCNAMEValue"`
SafeToRemoveRevokedKeyFromDNS bool `json:"SafeToRemoveRevokedKeyFromDNS"`
}
DomainDetails — полные сведения о домене, включая DNS-записи. SPFTextValue и DKIMTextValue API отдаёт объектами DNS-записи.
type Error ¶
type Error struct {
// StatusCode — HTTP-код ответа.
StatusCode int
// ErrorCode — код ошибки API из тела ответа (0, если тело не разобрано).
ErrorCode int
// Message — описание ошибки из тела ответа.
Message string
// Body — сырое тело ответа.
Body []byte
}
Error — ошибка, возвращённая API Haskimail.
type HTTPAuth ¶
type HTTPAuth struct {
Username string `json:"Username,omitempty"`
Password string `json:"Password,omitempty"`
}
HTTPAuth — Basic-аутентификация для вызова вебхука.
type Message ¶
type Message struct {
MessageStream string `json:"MessageStream,omitempty"`
From string `json:"From,omitempty"`
To string `json:"To,omitempty"`
Cc string `json:"Cc,omitempty"`
Bcc string `json:"Bcc,omitempty"`
ReplyTo string `json:"ReplyTo,omitempty"`
Subject string `json:"Subject,omitempty"`
HTMLBody string `json:"HtmlBody,omitempty"`
TextBody string `json:"TextBody,omitempty"`
Tag string `json:"Tag,omitempty"`
Headers []Header `json:"Headers,omitempty"`
Attachments []Attachment `json:"Attachments,omitempty"`
TrackOpens *bool `json:"TrackOpens,omitempty"`
TrackLinks string `json:"TrackLinks,omitempty"`
Metadata map[string]string `json:"Metadata,omitempty"`
}
Message — письмо для отправки через /email и /email/batch.
func (*Message) AddAttachment ¶
func (m *Message) AddAttachment(a Attachment)
AddAttachment добавляет вложение.
func (*Message) AddMetadata ¶
AddMetadata добавляет пару ключ-значение в метаданные.
type MessageResponse ¶
type MessageResponse struct {
ErrorCode int `json:"ErrorCode"`
Message string `json:"Message"`
To string `json:"To,omitempty"`
Cc string `json:"Cc,omitempty"`
Bcc string `json:"Bcc,omitempty"`
SubmittedAt *Time `json:"SubmittedAt,omitempty"`
MessageID string `json:"MessageID,omitempty"`
}
MessageResponse — результат отправки письма.
type MessageStream ¶
type MessageStream struct {
ID string `json:"ID,omitempty"`
ServerID int64 `json:"ServerID,omitempty"`
Name string `json:"Name,omitempty"`
Description string `json:"Description,omitempty"`
MessageStreamType string `json:"MessageStreamType,omitempty"`
CreatedAt *Time `json:"CreatedAt,omitempty"`
UpdatedAt *Time `json:"UpdatedAt,omitempty"`
ArchivedAt *Time `json:"ArchivedAt,omitempty"`
SubscriptionManagementConfiguration *SubscriptionManagementConfiguration `json:"SubscriptionManagementConfiguration,omitempty"`
}
MessageStream — канал отправки. ID — числовой ID канала строкой («2081»), его передают в Message.MessageStream. Имена JSON-полей совпадают с API: при создании канала сервер читает ServerID с учётом регистра.
type MessageStreamArchiveResponse ¶
type MessageStreamArchiveResponse struct {
ID string `json:"ID"`
ServerID int64 `json:"ServerID"`
ArchivedAt *Time `json:"ArchivedAt"`
ExpectedPurgeDate *Time `json:"ExpectedPurgeDate"`
}
MessageStreamArchiveResponse — результат архивации канала.
type MessageStreamUnarchiveResponse ¶
type MessageStreamUnarchiveResponse = MessageStream
MessageStreamUnarchiveResponse — результат разархивации канала.
type MessageStreams ¶
type MessageStreams struct {
TotalCount int `json:"TotalCount"`
MessageStreams []MessageStream `json:"MessageStreams"`
}
MessageStreams — список каналов.
type NamedCountStat ¶ added in v1.3.0
NamedCountStat — счётчики за день по названиям: почтовым клиентам или браузерам. В JSON названия — ключи объекта рядом с Date.
func (*NamedCountStat) UnmarshalJSON ¶ added in v1.3.0
func (s *NamedCountStat) UnmarshalJSON(b []byte) error
UnmarshalJSON разбирает день: Date — дата, остальные ключи — названия со счётчиками.
type NamedCountStats ¶ added in v1.3.0
type NamedCountStats struct {
Days []NamedCountStat
Totals map[string]int
}
NamedCountStats — открытия по почтовым клиентам или клики по браузерам: по дням и итог за период (Totals). В JSON итоги — ключи объекта рядом с Days.
func (*NamedCountStats) UnmarshalJSON ¶ added in v1.3.0
func (s *NamedCountStats) UnmarshalJSON(b []byte) error
UnmarshalJSON разбирает ответ: Days — дни, остальные ключи — итоги по названиям.
type OpenStat ¶
type OpenStat struct {
Date *Time `json:"Date"`
Opens int `json:"Opens"`
Unique int `json:"Unique"`
}
OpenStat — открытия за день.
type OpenWebhook ¶
type OpenWebhook struct {
OutboundMessageOpen
FirstOpen bool `json:"FirstOpen"`
Metadata map[string]string `json:"Metadata"`
}
OpenWebhook — событие открытия.
type OpenWebhookTrigger ¶
type OpenWebhookTrigger struct {
Enabled *bool `json:"Enabled,omitempty"`
PostFirstOpenOnly *bool `json:"PostFirstOpenOnly,omitempty"`
}
OpenWebhookTrigger — триггер открытий.
type Option ¶
type Option func(*config)
Option настраивает клиент при создании.
func WithBaseURL ¶
WithBaseURL задаёт пользовательский хост API (без схемы), например "api.example.ru".
func WithConnectTimeout ¶
WithConnectTimeout задаёт таймаут установки TCP-соединения.
func WithHTTPClient ¶
WithHTTPClient задаёт собственный *http.Client. В этом случае WithConnectTimeout и WithReadTimeout не применяются.
func WithHeader ¶
WithHeader добавляет произвольный заголовок ко всем запросам.
func WithInsecure ¶
func WithInsecure() Option
WithInsecure переключает клиент на HTTP вместо HTTPS.
func WithReadTimeout ¶
WithReadTimeout задаёт таймаут ожидания заголовков ответа.
func WithSecureConnection ¶
WithSecureConnection явно задаёт протокол: true — HTTPS, false — HTTP.
func WithUserAgent ¶
WithUserAgent переопределяет заголовок User-Agent.
type OutboundBounceStats ¶
type OutboundBounceStats = DayStats[BounceStat]
Псевдонимы для конкретных видов статистики.
type OutboundClickBrowserStats ¶ added in v1.3.0
type OutboundClickBrowserStats = NamedCountStats
Псевдонимы для разбивки по названиям.
type OutboundClickPlatformStats ¶
type OutboundClickPlatformStats = PlatformStats
Псевдонимы для разбивки по платформам.
type OutboundClickStats ¶
Псевдонимы для конкретных видов статистики.
type OutboundMessage ¶
type OutboundMessage struct {
Recipient string `json:"Recipient"`
ReceivedAt *Time `json:"ReceivedAt"`
Tag string `json:"Tag"`
From string `json:"From"`
Status string `json:"Status"`
MessageID string `json:"MessageID"`
Subject string `json:"Subject"`
MessageStream string `json:"MessageStream"`
}
OutboundMessage — исходящее сообщение в поиске.
type OutboundMessageClick ¶
type OutboundMessageClick struct {
OutboundMessageOpen
OriginalLink string `json:"OriginalLink"`
ClickLocation string `json:"ClickLocation"`
}
OutboundMessageClick — событие клика по ссылке.
type OutboundMessageClicks ¶
type OutboundMessageClicks struct {
TotalCount int `json:"TotalCount"`
Clicks []OutboundMessageClick `json:"Clicks"`
}
OutboundMessageClicks — страница кликов.
type OutboundMessageDetails ¶
type OutboundMessageDetails struct {
OutboundMessage
TextBody string `json:"TextBody"`
HTMLBody string `json:"HtmlBody"`
Body string `json:"Body"`
MessageEvents []OutboundMessageDetailsEvent `json:"MessageEvents"`
}
OutboundMessageDetails — подробности сообщения.
type OutboundMessageDetailsEvent ¶
type OutboundMessageDetailsEvent struct {
Recipient string `json:"Recipient"`
Type string `json:"Type"`
ReceivedAt *Time `json:"ReceivedAt"`
Details map[string]string `json:"Details"`
}
OutboundMessageDetailsEvent — событие жизненного цикла сообщения.
type OutboundMessageOpen ¶
type OutboundMessageOpen struct {
Recipient string `json:"Recipient"`
ReceivedAt *Time `json:"ReceivedAt"`
Tag string `json:"Tag"`
From string `json:"From"`
RecordType string `json:"RecordType"`
OS string `json:"Os"`
Browser string `json:"Browser"`
Webservice string `json:"Webservice"`
UserAgent string `json:"UserAgent"`
Language string `json:"Language"`
Region string `json:"Region"`
Country string `json:"Country"`
MessageID string `json:"MessageID"`
Subject string `json:"Subject"`
MessageStream string `json:"MessageStream"`
}
OutboundMessageOpen — событие открытия письма.
type OutboundMessageOpens ¶
type OutboundMessageOpens struct {
TotalCount int `json:"TotalCount"`
Opens []OutboundMessageOpen `json:"Opens"`
}
OutboundMessageOpens — страница открытий.
type OutboundMessages ¶
type OutboundMessages struct {
TotalCount int `json:"TotalCount"`
Messages []OutboundMessage `json:"Messages"`
}
OutboundMessages — страница результатов поиска сообщений.
type OutboundOpenEmailClientStats ¶ added in v1.3.0
type OutboundOpenEmailClientStats = NamedCountStats
Псевдонимы для разбивки по названиям.
type OutboundOpenPlatformStats ¶
type OutboundOpenPlatformStats = PlatformStats
Псевдонимы для разбивки по платформам.
type OutboundOpenStats ¶
Псевдонимы для конкретных видов статистики.
type OutboundSendStats ¶
Псевдонимы для конкретных видов статистики.
type OutboundSpamStats ¶
Псевдонимы для конкретных видов статистики.
type OutboundStats ¶
type OutboundStats struct {
Sent int `json:"Sent"`
Bounced int `json:"Bounced"`
SMTPAPIErrors int `json:"SmtpApiErrors"`
BounceRate float64 `json:"BounceRate"`
SpamComplaintsRate float64 `json:"SpamComplaintsRate"`
Opens int `json:"Opens"`
UniqueOpens int `json:"UniqueOpens"`
Tracked int `json:"Tracked"`
WithLinkTracking int `json:"WithLinkTracking"`
WithOpenTracking int `json:"WithOpenTracking"`
TotalTrackedLinksSent int `json:"TotalTrackedLinksSent"`
UniqueLinksClicked int `json:"UniqueLinksClicked"`
TotalClicks int `json:"TotalClicks"`
WithClientRecorded int `json:"WithClientRecorded"`
WithPlatformRecorded int `json:"WithPlatformRecorded"`
WithReadTimeRecorded int `json:"WithReadTimeRecorded"`
SpamComplaints int `json:"SpamComplaints"`
// Opened и Clicked — открытия и клики за период, включая повторные.
Opened int `json:"Opened"`
Clicked int `json:"Clicked"`
// Unsubscribed — адресов, отписавшихся за период (в API поле называется Unsubsribed).
Unsubscribed int `json:"Unsubsribed"`
OpenRate float64 `json:"OpenRate"`
ClickRate float64 `json:"ClickRate"`
}
OutboundStats — сводная статистика исходящих писем.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params — параметры строки запроса (пагинация, фильтры). Нулевое значение и nil готовы к использованию.
p := haskimail.NewParams().Int("count", 50).Int("offset", 0).String("tag", "welcome")
type PlatformStat ¶
type PlatformStat struct {
Date *Time `json:"Date"`
Desktop int `json:"Desktop"`
Mobile int `json:"Mobile"`
WebMail int `json:"WebMail"`
Unknown int `json:"Unknown"`
}
PlatformStat — открытия или клики за день по платформам: Desktop — компьютер, Mobile — телефон или планшет, WebMail — веб-почта (Gmail, Mail.ru, Яндекс, Рамблер), Unknown — не определилось, в том числе боты.
type PlatformStats ¶ added in v1.3.0
type PlatformStats struct {
Days []PlatformStat `json:"Days"`
Desktop int `json:"Desktop"`
Mobile int `json:"Mobile"`
WebMail int `json:"WebMail"`
Unknown int `json:"Unknown"`
}
PlatformStats — открытия или клики по платформам: по дням и итог за период.
type RequestResponse ¶
RequestResponse — стандартный ответ API на операции без данных (например, удаление).
type Server ¶
type Server struct {
ID int64 `json:"ID,omitempty"`
Name string `json:"Name,omitempty"`
Color string `json:"Color,omitempty"`
APITokens []string `json:"ApiTokens,omitempty"`
DeliveryHookURL string `json:"DeliveryHookUrl,omitempty"`
BounceHookURL string `json:"BounceHookUrl,omitempty"`
OpenHookURL string `json:"OpenHookUrl,omitempty"`
ClickHookURL string `json:"ClickHookUrl,omitempty"`
TrackOpens *bool `json:"TrackOpens,omitempty"`
TrackLinks string `json:"TrackLinks,omitempty"`
PostFirstOpenOnly *bool `json:"PostFirstOpenOnly,omitempty"`
InboundAddress string `json:"InboundAddress,omitempty"`
InboundDomain string `json:"InboundDomain,omitempty"`
InboundHash string `json:"InboundHash,omitempty"`
InboundSpamThreshold *int `json:"InboundSpamThreshold,omitempty"`
SMTPAPIActivated *bool `json:"SmtpApiActivated,omitempty"`
RawEmailEnabled *bool `json:"RawEmailEnabled,omitempty"`
EnableSMTPAPIErrorHooks *bool `json:"EnableSmtpApiErrorHooks,omitempty"`
IncludeBounceContentInHook *bool `json:"IncludeBounceContentInHook,omitempty"`
ServerLink string `json:"ServerLink,omitempty"`
DeliveryType string `json:"DeliveryType,omitempty"`
}
Server — сервер (набор настроек отправки) в аккаунте.
type SpamWebhookTrigger ¶
type SpamWebhookTrigger = BounceWebhookTrigger
SpamWebhookTrigger — триггер жалоб на спам.
type SubscriptionChange ¶
type SubscriptionChange = WebhookTrigger
SubscriptionChange — триггер изменения подписки.
type SubscriptionManagementConfiguration ¶
type SubscriptionManagementConfiguration struct {
// UnsubscribeHandlingType: "Haskimail" (по умолчанию) или "Custom".
UnsubscribeHandlingType string `json:"UnsubscribeHandlingType,omitempty"`
}
SubscriptionManagementConfiguration — настройки обработки отписок.
type Suppression ¶
type Suppression struct {
EmailAddress string `json:"EmailAddress"`
SuppressionReason string `json:"SuppressionReason"`
Origin string `json:"Origin"`
CreatedAt *Time `json:"CreatedAt"`
}
Suppression — запись стоп-листа.
type SuppressionEntries ¶
type SuppressionEntries struct {
Suppressions []SuppressionEntry `json:"Suppressions"`
}
SuppressionEntries — тело запроса на изменение стоп-листа.
func NewSuppressionEntries ¶
func NewSuppressionEntries(emails ...string) SuppressionEntries
NewSuppressionEntries собирает тело запроса из списка адресов.
type SuppressionEntry ¶
type SuppressionEntry struct {
EmailAddress string `json:"EmailAddress"`
}
SuppressionEntry — адрес для добавления/удаления.
type SuppressionStatus ¶
type SuppressionStatus struct {
EmailAddress string `json:"EmailAddress"`
Status string `json:"Status"`
Message string `json:"Message"`
}
SuppressionStatus — результат операции для одного адреса.
type SuppressionStatuses ¶
type SuppressionStatuses struct {
Suppressions []SuppressionStatus `json:"Suppressions"`
}
SuppressionStatuses — результаты операции над стоп-листом.
type Suppressions ¶
type Suppressions struct {
Suppressions []Suppression `json:"Suppressions"`
}
Suppressions — список записей стоп-листа.
type Template ¶
type Template struct {
BaseTemplate
Subject string `json:"Subject,omitempty"`
HTMLBody string `json:"HtmlBody,omitempty"`
TextBody string `json:"TextBody,omitempty"`
AssociatedServerID int64 `json:"AssociatedServerId,omitempty"`
}
Template — шаблон целиком; используется и в запросах создания/изменения.
type TemplateContent ¶
type TemplateContent struct {
Subject string `json:"Subject,omitempty"`
HTMLBody string `json:"HtmlBody,omitempty"`
TextBody string `json:"TextBody,omitempty"`
}
TemplateContent — содержимое шаблона.
type TemplateToValidate ¶
type TemplateToValidate struct {
Subject string `json:"Subject,omitempty"`
HTMLBody string `json:"HtmlBody,omitempty"`
TextBody string `json:"TextBody,omitempty"`
TestRenderModel any `json:"TestRenderModel,omitempty"`
}
TemplateToValidate — шаблон для проверки (ValidateTemplate). Нужен хотя бы один из Subject, HTMLBody, TextBody. TestRenderModel подставляется буквально, как TemplateModel при отправке: ключ — фрагмент вместе с разделителями, map[string]string{"{{name}}": "Иван"}.
type TemplateValidation ¶
type TemplateValidation struct {
AllContentIsValid bool `json:"AllContentIsValid"`
Subject *TemplateValidationField `json:"Subject,omitempty"`
HTMLBody *TemplateValidationField `json:"HtmlBody,omitempty"`
TextBody *TemplateValidationField `json:"TextBody,omitempty"`
// SuggestedTemplateModel — все {{…}} шаблона с значениями из TestRenderModel
// или заглушками «имя_Value».
SuggestedTemplateModel map[string]string `json:"SuggestedTemplateModel"`
}
TemplateValidation — результат проверки шаблона. Части, которой не было в запросе, нет и в ответе (nil).
type TemplateValidationError ¶ added in v1.3.0
type TemplateValidationError struct {
Message string `json:"Message"`
Line int `json:"Line"`
CharacterPosition int `json:"CharacterPosition"`
}
TemplateValidationError — фрагмент {{…}} без значения или «{{» без пары. Line и CharacterPosition считаются с 1 в исходном тексте; 0 — фрагмент принесло значение модели.
type TemplateValidationField ¶
type TemplateValidationField struct {
ContentIsValid bool `json:"ContentIsValid"`
ValidationErrors []TemplateValidationError `json:"ValidationErrors"`
// RenderedContent — часть после подстановки, как её получит получатель.
RenderedContent string `json:"RenderedContent"`
}
TemplateValidationField — результат проверки одной части шаблона.
type TemplatedMessage ¶
type TemplatedMessage struct {
TemplateID int64 `json:"TemplateId,omitempty"`
TemplateAlias string `json:"TemplateAlias,omitempty"`
TemplateModel any `json:"TemplateModel,omitempty"`
InlineCSS *bool `json:"InlineCss,omitempty"`
From string `json:"From,omitempty"`
To string `json:"To,omitempty"`
Cc string `json:"Cc,omitempty"`
Bcc string `json:"Bcc,omitempty"`
ReplyTo string `json:"ReplyTo,omitempty"`
Tag string `json:"Tag,omitempty"`
Headers []Header `json:"Headers,omitempty"`
Attachments []Attachment `json:"Attachments,omitempty"`
MessageStream string `json:"MessageStream,omitempty"`
TrackOpens *bool `json:"TrackOpens,omitempty"`
TrackLinks string `json:"TrackLinks,omitempty"`
Metadata map[string]string `json:"Metadata,omitempty"`
}
TemplatedMessage — письмо, отправляемое по шаблону. Укажите TemplateID или TemplateAlias.
func (*TemplatedMessage) AddAttachment ¶
func (m *TemplatedMessage) AddAttachment(a Attachment)
AddAttachment добавляет вложение.
func (*TemplatedMessage) AddHeader ¶
func (m *TemplatedMessage) AddHeader(name, value string)
AddHeader добавляет заголовок.
func (*TemplatedMessage) AddMetadata ¶
func (m *TemplatedMessage) AddMetadata(key, value string)
AddMetadata добавляет пару ключ-значение в метаданные.
type Templates ¶
type Templates struct {
TotalCount int `json:"TotalCount"`
Templates []BaseTemplate `json:"Templates"`
}
Templates — страница списка шаблонов.
type TemplatesPush ¶
type TemplatesPush struct {
TotalCount int `json:"TotalCount"`
Templates []TemplatesPushAction `json:"Templates"`
}
TemplatesPush — результат пуша шаблонов.
type TemplatesPushAction ¶
type TemplatesPushAction struct {
Action string `json:"Action"`
TemplateID int64 `json:"TemplateId"`
Alias string `json:"Alias"`
Name string `json:"Name"`
}
TemplatesPushAction — действие над шаблоном при пуше.
type TemplatesPushRequest ¶
type TemplatesPushRequest struct {
SourceServerID int64 `json:"SourceServerID"`
DestinationServerID int64 `json:"DestinationServerID"`
PerformChanges *bool `json:"PerformChanges,omitempty"`
}
TemplatesPushRequest — запрос на перенос шаблонов между серверами. Имена полей — как в API: сервер читает их с учётом регистра.
type Time ¶
Time — дата/время API. Разбирает все форматы, встречающиеся в ответах Haskimail.
func (Time) MarshalJSON ¶
MarshalJSON реализует json.Marshaler (RFC 3339).
func (*Time) UnmarshalJSON ¶
UnmarshalJSON реализует json.Unmarshaler.
type Webhook ¶
type Webhook struct {
ID int64 `json:"ID,omitempty"`
URL string `json:"Url,omitempty"`
HTTPAuth *HTTPAuth `json:"HttpAuth,omitempty"`
HTTPHeaders []Header `json:"HttpHeaders,omitempty"`
MessageStream string `json:"MessageStream,omitempty"`
Triggers *WebhookTriggers `json:"Triggers,omitempty"`
}
Webhook — настройка вебхука.
type WebhookTrigger ¶
type WebhookTrigger struct {
Enabled *bool `json:"Enabled,omitempty"`
}
WebhookTrigger — базовый триггер (клик, доставка).
type WebhookTriggers ¶
type WebhookTriggers struct {
Open *OpenWebhookTrigger `json:"Open,omitempty"`
Click *WebhookTrigger `json:"Click,omitempty"`
Delivery *WebhookTrigger `json:"Delivery,omitempty"`
Bounce *BounceWebhookTrigger `json:"Bounce,omitempty"`
SpamComplaint *SpamWebhookTrigger `json:"SpamComplaint,omitempty"`
SubscriptionChange *SubscriptionChange `json:"SubscriptionChange,omitempty"`
}
WebhookTriggers — набор триггеров вебхука.