Files
davidandClaude Opus 5.5 b6758417a3 Prospects: Listmonk mailing lists, and their opt-outs
Settings → Email → Mailing lists connects Listmonk (the Core's, by
default) with an API user and its token; Test reads the lists. A person
in Review can be added to a list, with their company, title and signal:
a double opt-in list asks them to confirm unless they already agreed; a
single opt-in list takes them only once they have; a suppressed address
is refused. Their card shows the lists they're on (a new list_members
table). Every hour, or on Sync now, everyone blocklisted in Listmonk or
unsubscribed from one of its lists goes on the suppression list, with
the reason; an address already there keeps its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:15:37 -07:00

231 lines
6.8 KiB
Go

// Package listmonk adds people to mailing lists on a Listmonk server
// (https://listmonk.app/docs/apis/apis/), such as the one on a Federated
// Core. It reads the lists and adds subscribers; it never sends campaigns.
package listmonk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// ErrUnauthorized means the API user or its token was refused.
var ErrUnauthorized = errors.New("Listmonk refused the API user or its token")
// Client calls one Listmonk as one API user.
type Client struct {
base, user, token string
http *http.Client
}
// New takes Listmonk's address and an API user with its token (Listmonk:
// Admin → Users → API user).
func New(base, user, token string) *Client {
return &Client{base: strings.TrimRight(strings.TrimSpace(base), "/"), user: strings.TrimSpace(user), token: strings.TrimSpace(token),
http: &http.Client{Timeout: 30 * time.Second}}
}
func (c *Client) do(ctx context.Context, method, path string, in, out any) (int, error) {
var body io.Reader
if in != nil {
raw, err := json.Marshal(in)
if err != nil {
return 0, err
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
if err != nil {
return 0, err
}
req.Header.Set("Authorization", "token "+c.user+":"+c.token)
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
res, err := c.http.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
if err != nil {
return res.StatusCode, err
}
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
return res.StatusCode, ErrUnauthorized
}
if res.StatusCode >= 300 {
var e struct {
Message string `json:"message"`
}
if json.Unmarshal(raw, &e) == nil && e.Message != "" {
return res.StatusCode, fmt.Errorf("Listmonk: %s", e.Message)
}
return res.StatusCode, fmt.Errorf("Listmonk: HTTP %d", res.StatusCode)
}
if out != nil {
var env struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(raw, &env); err != nil {
return res.StatusCode, fmt.Errorf("Listmonk: %w", err)
}
return res.StatusCode, json.Unmarshal(env.Data, out)
}
return res.StatusCode, nil
}
// List is a mailing list.
type List struct {
ID int64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // public, private
Optin string `json:"optin"` // single, double
Subscribers int `json:"subscriber_count"`
}
// Double says whether people must confirm before they get the list's mail.
func (l List) Double() bool { return l.Optin == "double" }
// Lists are the server's mailing lists.
func (c *Client) Lists(ctx context.Context) ([]List, error) {
var out struct {
Results []List `json:"results"`
}
_, err := c.do(ctx, http.MethodGet, "/api/lists?per_page=all", nil, &out)
return out.Results, err
}
// Subscriber is someone to add.
type Subscriber struct {
Email string
Name string
Attribs map[string]any // kept with them in Listmonk
}
// Subscribe adds someone to a list. confirmed says they've already agreed
// to receive it; otherwise a double opt-in list asks them by email first.
// It returns the subscriber's ID, and whether they were already in
// Listmonk (on any list).
func (c *Client) Subscribe(ctx context.Context, s Subscriber, list List, confirmed bool) (id int64, existed bool, err error) {
var created struct {
ID int64 `json:"id"`
}
status, err := c.do(ctx, http.MethodPost, "/api/subscribers", map[string]any{
"email": s.Email, "name": s.Name, "status": "enabled", "lists": []int64{list.ID},
"attribs": s.Attribs, "preconfirm_subscriptions": confirmed,
}, &created)
if err == nil {
return created.ID, false, nil
}
if status != http.StatusConflict {
return 0, false, err
}
// Already a subscriber: add them to this list too.
id, err = c.find(ctx, s.Email)
if err != nil {
return 0, true, err
}
subStatus := "unconfirmed"
if confirmed || !list.Double() {
subStatus = "confirmed"
}
if _, err := c.do(ctx, http.MethodPut, "/api/subscribers/lists", map[string]any{
"ids": []int64{id}, "action": "add", "target_list_ids": []int64{list.ID}, "status": subStatus,
}, nil); err != nil {
return id, true, err
}
if subStatus == "unconfirmed" {
// Ask them to confirm, as a new subscriber would be asked.
if _, err := c.do(ctx, http.MethodPost, "/api/subscribers/"+strconv.FormatInt(id, 10)+"/optin", nil, nil); err != nil {
return id, true, err
}
}
return id, true, nil
}
// find is a subscriber's ID by email.
func (c *Client) find(ctx context.Context, email string) (int64, error) {
q := url.Values{"query": {"subscribers.email = '" + strings.ReplaceAll(strings.ToLower(email), "'", "''") + "'"}, "per_page": {"1"}}
var out struct {
Results []struct {
ID int64 `json:"id"`
} `json:"results"`
}
if _, err := c.do(ctx, http.MethodGet, "/api/subscribers?"+q.Encode(), nil, &out); err != nil {
return 0, err
}
if len(out.Results) == 0 {
return 0, errors.New("Listmonk says the address exists, but couldn't find it")
}
return out.Results[0].ID, nil
}
// OptedOut is someone who doesn't want mail: blocklisted (from all lists)
// or unsubscribed from one list.
type OptedOut struct {
Email string
List string // the list they left; "" when blocklisted
}
// pageSize is how many subscribers one request reads.
const pageSize = 1000
// subscribers reads every page of a subscriber query.
func (c *Client) subscribers(ctx context.Context, q url.Values) ([]string, error) {
var out []string
for page := 1; page < 1000; page++ {
q.Set("per_page", strconv.Itoa(pageSize))
q.Set("page", strconv.Itoa(page))
var res struct {
Results []struct {
Email string `json:"email"`
} `json:"results"`
Total int `json:"total"`
}
if _, err := c.do(ctx, http.MethodGet, "/api/subscribers?"+q.Encode(), nil, &res); err != nil {
return out, err
}
for _, r := range res.Results {
if r.Email != "" {
out = append(out, strings.ToLower(r.Email))
}
}
if len(res.Results) < pageSize || len(out) >= res.Total {
return out, nil
}
}
return out, nil
}
// OptedOut lists everyone blocklisted, and everyone unsubscribed from any
// of the lists.
func (c *Client) OptedOut(ctx context.Context, lists []List) ([]OptedOut, error) {
var out []OptedOut
blocked, err := c.subscribers(ctx, url.Values{"query": {"subscribers.status = 'blocklisted'"}})
if err != nil {
return nil, err
}
for _, e := range blocked {
out = append(out, OptedOut{Email: e})
}
for _, l := range lists {
left, err := c.subscribers(ctx, url.Values{"list_id": {strconv.FormatInt(l.ID, 10)}, "subscription_status": {"unsubscribed"}})
if err != nil {
return out, fmt.Errorf("%s: %w", l.Name, err)
}
for _, e := range left {
out = append(out, OptedOut{Email: e, List: l.Name})
}
}
return out, nil
}