Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Contact management:
Email marketing:

- Email campaigns — create, list, update & delete campaigns, schedule/start lifecycle & stats — [`examples/email-campaigns`](examples/email-campaigns)
- Marketing stats — aggregated across campaigns & automations, filtered by sending domain, source & ESP — [`examples/marketing-stats`](examples/marketing-stats)

## Errors

Expand Down
3 changes: 3 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ type Client struct {

// EmailCampaigns manages email marketing campaigns and their statistics.
EmailCampaigns *EmailCampaignsService
// MarketingStats reads Email Marketing stats across campaigns and automations.
MarketingStats *MarketingStatsService
}

// Ptr returns a pointer to v, for setting optional pointer request fields such
Expand Down Expand Up @@ -183,6 +185,7 @@ func NewClient(token string, opts ...Option) (*Client, error) {
c.ContactImports = &ContactImportsService{client: c}
c.ContactExports = &ContactExportsService{client: c}
c.EmailCampaigns = &EmailCampaignsService{client: c}
c.MarketingStats = &MarketingStatsService{client: c}

return c, nil
}
Expand Down
44 changes: 44 additions & 0 deletions examples/marketing-stats/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"context"
"fmt"
"log"
"os"
"time"

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

func main() {
client, err := mailtrap.NewClient(os.Getenv("MAILTRAP_API_TOKEN"))
if err != nil {
log.Fatal(err)
}

ctx := context.Background()
now := time.Now().UTC()
opts := &mailtrap.MarketingStatsOptions{
StartDate: now.AddDate(0, 0, -30).Format(time.DateOnly),
EndDate: now.Format(time.DateOnly),
}

// Campaigns and automations together.
stats, _, err := client.MarketingStats.Get(ctx, opts)
if err != nil {
log.Fatal(err)
}
printStats("all", stats)

// Campaigns only.
opts.Sources = []string{mailtrap.MarketingStatsSourceCampaigns}
stats, _, err = client.MarketingStats.Get(ctx, opts)
if err != nil {
log.Fatal(err)
}
printStats("campaigns", stats)
}

func printStats(label string, s *mailtrap.MarketingStats) {
fmt.Printf("%s: delivered %d (%.0f%%), opened %d (%.0f%%)\n", label, s.DeliveryCount, s.DeliveryRate*100, s.OpenCount, s.OpenRate*100)
}
87 changes: 87 additions & 0 deletions marketing_stats.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package mailtrap

import (
"context"
"net/http"
"net/url"
"strconv"
)

// MarketingStatsService reads aggregated Email Marketing statistics across
// campaigns and automations.
type MarketingStatsService struct {
client *Client
}

// Email Marketing sources for MarketingStatsOptions.Sources.
const (
MarketingStatsSourceCampaigns = "campaigns"
MarketingStatsSourceAutomations = "automations"
)

// MarketingStats holds the Email Marketing counts and rates for a period.
// Rates are fractions in the range 0..1: delivery and bounce rates are
// relative to SentCount, the open, click, spam and unsubscription rates to
// DeliveryCount. Every value is 0 when nothing matched the filters.
type MarketingStats struct {
DeliveryCount int64 `json:"delivery_count"`
DeliveryRate float64 `json:"delivery_rate"`
BounceCount int64 `json:"bounce_count"`
BounceRate float64 `json:"bounce_rate"`
OpenCount int64 `json:"open_count"`
OpenRate float64 `json:"open_rate"`
ClickCount int64 `json:"click_count"`
ClickRate float64 `json:"click_rate"`
SpamCount int64 `json:"spam_count"`
SpamRate float64 `json:"spam_rate"`
UnsubscriptionCount int64 `json:"unsubscription_count"`
UnsubscriptionRate float64 `json:"unsubscription_rate"`
SentCount int64 `json:"sent_count"`
}

// MarketingStatsOptions filters a marketing stats query. StartDate and EndDate
// (YYYY-MM-DD) are required; the remaining fields narrow the results and may
// be omitted.
type MarketingStatsOptions struct {
StartDate string
EndDate string
SendingDomainIDs []int64
// Sources narrows the stats to MarketingStatsSourceCampaigns or
// MarketingStatsSourceAutomations; omit it, or pass both, for all Email
// Marketing traffic.
Sources []string
EmailServiceProviders []string
}

func (o *MarketingStatsOptions) values() url.Values {
v := url.Values{}
if o == nil {
return v
}
if o.StartDate != "" {
v.Set("start_date", o.StartDate)
}
if o.EndDate != "" {
v.Set("end_date", o.EndDate)
}
for _, id := range o.SendingDomainIDs {
v.Add("sending_domain_ids[]", strconv.FormatInt(id, 10))
}
for _, s := range o.Sources {
v.Add("sources[]", s)
}
for _, esp := range o.EmailServiceProviders {
v.Add("email_service_providers[]", esp)
}
return v
}

// Get returns the account's aggregated Email Marketing stats for the period:
// the numbers the Email Marketing Stats Overview shows.
func (s *MarketingStatsService) Get(ctx context.Context, opts *MarketingStatsOptions) (*MarketingStats, *Response, error) {
var wrapper struct {
Data *MarketingStats `json:"data"`
}
resp, err := s.client.do(ctx, HostGeneral, http.MethodGet, "/api/marketing/stats", opts.values(), nil, &wrapper)
return wrapper.Data, resp, err
}
87 changes: 87 additions & 0 deletions marketing_stats_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package mailtrap_test

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

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

func TestMarketingStats_Get(t *testing.T) {
mux, client := setup(t)
mux.HandleFunc("GET /api/marketing/stats", func(w http.ResponseWriter, r *http.Request) {
want := map[string][]string{
"start_date": {"2026-05-01"},
"end_date": {"2026-05-31"},
"sending_domain_ids[]": {"3938", "3939"},
"sources[]": {"campaigns"},
"email_service_providers[]": {"Google", "Yahoo"},
}
if got := map[string][]string(r.URL.Query()); !reflect.DeepEqual(got, want) {
t.Errorf("query = %v, want %v", got, want)
}
_, _ = w.Write([]byte(`{"data": {
"delivery_count": 1450,
"delivery_rate": 0.9667,
"bounce_count": 30,
"bounce_rate": 0.02,
"open_count": 820,
"open_rate": 0.5655,
"click_count": 310,
"click_rate": 0.2138,
"spam_count": 5,
"spam_rate": 0.0033,
"unsubscription_count": 12,
"unsubscription_rate": 0.0083,
"sent_count": 1500
}}`))
})

stats, _, err := client.MarketingStats.Get(context.Background(), &mailtrap.MarketingStatsOptions{
StartDate: "2026-05-01",
EndDate: "2026-05-31",
SendingDomainIDs: []int64{3938, 3939},
Sources: []string{mailtrap.MarketingStatsSourceCampaigns},
EmailServiceProviders: []string{"Google", "Yahoo"},
})
if err != nil {
t.Fatalf("Get: %v", err)
}
want := &mailtrap.MarketingStats{
DeliveryCount: 1450, DeliveryRate: 0.9667,
BounceCount: 30, BounceRate: 0.02,
OpenCount: 820, OpenRate: 0.5655,
ClickCount: 310, ClickRate: 0.2138,
SpamCount: 5, SpamRate: 0.0033,
UnsubscriptionCount: 12, UnsubscriptionRate: 0.0083,
SentCount: 1500,
}
if !reflect.DeepEqual(stats, want) {
t.Errorf("stats = %+v, want %+v", stats, want)
}
}

func TestMarketingStats_Get_DatesOnly(t *testing.T) {
mux, client := setup(t)
mux.HandleFunc("GET /api/marketing/stats", func(w http.ResponseWriter, r *http.Request) {
// Omitted filters send no keys.
want := map[string][]string{"start_date": {"2026-05-01"}, "end_date": {"2026-05-31"}}
if got := map[string][]string(r.URL.Query()); !reflect.DeepEqual(got, want) {
t.Errorf("query = %v, want %v", got, want)
}
_, _ = w.Write([]byte(`{"data": {}}`))
})

stats, _, err := client.MarketingStats.Get(context.Background(), &mailtrap.MarketingStatsOptions{
StartDate: "2026-05-01",
EndDate: "2026-05-31",
})
if err != nil {
t.Fatalf("Get: %v", err)
}
if !reflect.DeepEqual(stats, &mailtrap.MarketingStats{}) {
t.Errorf("stats = %+v, want zero value", stats)
}
}
Loading