Files
davidandClaude Opus 5.5 d23d5e2a87 Phase 2 part 7: the end of the funnel
Posts can be written for a buying signal: the prompt gets its hypothesis
and angle, and links carry its campaign tag. Plausible (Stats API v2) is
read once a day for visitors on tagged links, recorded per signal as
Visited. Stripe (restricted key) is read every hour: $0 checkouts are
Signed up, paid invoices and one-time payments are Paid with their value,
tied to a signal by the checkout's utm_campaign metadata or the payer's
email. The Core's Cal.com has no API, so booking emails from Cal.com in
the outreach mailbox count as Booked. New Settings → Website & sales;
the signal page lists its posts and tagged links. Schema 11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 06:42:03 -07:00

617 lines
17 KiB
Go

package outreach
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/client"
_ "github.com/emersion/go-message/charset" // replies in other character sets
gomail "github.com/emersion/go-message/mail"
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
// imapClient connects and signs in to the mailbox.
func imapClient(ctx context.Context, s Settings, password string) (*client.Client, error) {
host := s.IMAPHost
if host == "" {
host = s.SMTPHost
}
addr := net.JoinHostPort(host, strconv.Itoa(s.IMAPPort))
dialer := &net.Dialer{Timeout: 30 * time.Second}
if dl, ok := ctx.Deadline(); ok {
dialer.Deadline = dl
}
var c *client.Client
var err error
if s.Insecure {
c, err = client.DialWithDialer(dialer, addr)
} else {
c, err = client.DialWithDialerTLS(dialer, addr, &tls.Config{ServerName: host})
}
if err != nil {
return nil, fmt.Errorf("connecting to %s: %w", addr, err)
}
c.Timeout = time.Minute
if err := c.Login(s.Username, password); err != nil {
c.Logout()
return nil, fmt.Errorf("signing in to %s as %s: %w", host, s.Username, err)
}
return c, nil
}
// CheckIMAP signs in and opens the inbox, read-only. It returns how many
// messages the inbox has.
func CheckIMAP(ctx context.Context, s Settings, password string) (uint32, error) {
c, err := imapClient(ctx, s, password)
if err != nil {
return 0, err
}
defer c.Logout()
mbox, err := c.Select("INBOX", true)
if err != nil {
return 0, err
}
return mbox.Messages, nil
}
// SaveToSent puts a copy of a sent email in the mailbox's Sent folder, so
// it shows in the user's mail app with their other mail.
func SaveToSent(ctx context.Context, s Settings, password string, e *Email, now time.Time) error {
c, err := imapClient(ctx, s, password)
if err != nil {
return err
}
defer c.Logout()
ch := make(chan *imap.MailboxInfo, 50)
done := make(chan error, 1)
go func() { done <- c.List("", "*", ch) }()
sent := ""
for m := range ch {
for _, a := range m.Attributes {
if a == imap.SentAttr {
sent = m.Name
}
}
if sent == "" {
switch strings.ToLower(m.Name) {
case "sent", "sent items", "sent messages", "inbox.sent":
sent = m.Name
}
}
}
if err := <-done; err != nil {
return err
}
if sent == "" {
return errors.New("the mailbox has no Sent folder")
}
return c.Append(sent, []string{imap.SeenFlag}, now, bytes.NewBuffer(e.Raw))
}
// Check is the result of reading the inbox once.
type Check struct {
At time.Time `json:"at"`
Read int `json:"read"` // new messages looked at
Replies int `json:"replies"`
Stops int `json:"stops"`
Bounces int `json:"bounces"`
AutoReplies int `json:"auto_replies"`
Bookings int `json:"bookings"`
Error string `json:"error,omitempty"`
}
const (
checkKey = "outreach:last-check"
stateKey = "outreach:imap-state"
)
// inboxState is where the last read stopped.
type inboxState struct {
UIDValidity uint32 `json:"uid_validity"`
LastUID uint32 `json:"last_uid"`
}
// LastCheck is the last time the inbox was read, and what it found.
func LastCheck(d *db.DB) (*Check, error) {
var c Check
ok, err := d.GetJSON(checkKey, &c)
if err != nil || !ok {
return nil, err
}
return &c, nil
}
// maxRead is how many new messages one check looks at.
const maxRead = 500
// CheckReplies reads the inbox's new messages (read-only: nothing is marked
// read, moved or deleted) for replies to sent emails, bounces and requests
// to stop. A reply is matched by the Message-ID it answers, or else by
// coming from an address that was emailed.
func CheckReplies(ctx context.Context, d *db.DB, s Settings, password string, now time.Time) (*Check, error) {
res := &Check{At: now}
err := checkReplies(ctx, d, s, password, now, res)
if err != nil {
res.Error = err.Error()
}
if perr := d.PutJSON(checkKey, res); perr != nil && err == nil {
err = perr
}
return res, err
}
func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, now time.Time, res *Check) error {
var state inboxState
if _, err := d.GetJSON(stateKey, &state); err != nil {
return err
}
var first stringOrNull
if err := d.QueryRow(`SELECT min(sent_at) FROM outreach WHERE channel = 'email' AND sent_at IS NOT NULL`).Scan(&first); err != nil {
return err
}
c, err := imapClient(ctx, s, password)
if err != nil {
return err
}
defer c.Logout()
mbox, err := c.Select("INBOX", true)
if err != nil {
return err
}
var since time.Time
if first.Valid {
since, _ = time.Parse(timeFormat, first.String)
since = since.AddDate(0, 0, -1)
}
if s.BookingFrom != "" {
if b := now.AddDate(0, 0, -bookingDays); since.IsZero() || b.Before(since) {
since = b
}
}
if since.IsZero() {
// Nothing sent yet and no bookings to look for: start from here,
// without reading older mail.
return d.PutJSON(stateKey, inboxState{UIDValidity: mbox.UidValidity, LastUID: mbox.UidNext - 1})
}
criteria := imap.NewSearchCriteria()
if state.UIDValidity == mbox.UidValidity && state.LastUID > 0 {
criteria.Uid = new(imap.SeqSet)
criteria.Uid.AddRange(state.LastUID+1, 0)
} else {
criteria.Since = since
}
uids, err := c.UidSearch(criteria)
if err != nil {
return err
}
// "n:*" always includes the last message, even if it was read before.
var fresh []uint32
for _, u := range uids {
if u > state.LastUID || state.UIDValidity != mbox.UidValidity {
fresh = append(fresh, u)
}
}
if len(fresh) > maxRead {
fresh = fresh[:maxRead]
}
last := state.LastUID
if state.UIDValidity != mbox.UidValidity {
last = 0
}
for start := 0; start < len(fresh); start += 100 {
batch := fresh[start:min(start+100, len(fresh))]
if err := readBatch(c, d, s, batch, res); err != nil {
return err
}
last = max(last, batch[len(batch)-1])
if err := d.PutJSON(stateKey, inboxState{UIDValidity: mbox.UidValidity, LastUID: last}); err != nil {
return err
}
}
return nil
}
// stringOrNull scans a nullable text column.
type stringOrNull struct {
String string
Valid bool
}
func (s *stringOrNull) Scan(v any) error {
switch x := v.(type) {
case nil:
s.Valid = false
case string:
s.String, s.Valid = x, true
case []byte:
s.String, s.Valid = string(x), true
default:
return fmt.Errorf("unexpected %T", v)
}
return nil
}
var headerSection = &imap.BodySectionName{
BodyPartName: imap.BodyPartName{Specifier: imap.HeaderSpecifier,
Fields: []string{"In-Reply-To", "References", "Auto-Submitted", "X-Autoreply", "X-Autorespond", "Precedence", "Content-Type"}},
Peek: true,
}
var fullSection = &imap.BodySectionName{Peek: true}
// found is a message that answers, or bounces, one of ours.
type found struct {
uid uint32
booking bool
subject string
skip []string // addresses that aren't the attendee: ours, Cal.com's
msg *Message
bounce bool
id string // its Message-ID
date time.Time
}
// readBatch looks at the headers of some new messages, then reads the ones
// that concern outreach.
func readBatch(c *client.Client, d *db.DB, s Settings, uids []uint32, res *Check) error {
set := new(imap.SeqSet)
set.AddNum(uids...)
ch := make(chan *imap.Message, len(uids))
if err := c.UidFetch(set, []imap.FetchItem{imap.FetchUid, imap.FetchEnvelope, imap.FetchRFC822Size, headerSection.FetchItem()}, ch); err != nil {
return err
}
var todo []found
for m := range ch {
res.Read++
if m.Envelope == nil {
continue
}
var h mail.Header
if lit := m.GetBody(headerSection); lit != nil {
if parsed, err := mail.ReadMessage(io.MultiReader(lit, strings.NewReader("\r\n"))); err == nil {
h = parsed.Header
}
}
fromAddr := ""
if len(m.Envelope.From) > 0 {
fromAddr = strings.ToLower(m.Envelope.From[0].Address())
}
if s.BookingFrom != "" && fromAddr == strings.ToLower(s.BookingFrom) {
skip := []string{fromAddr, strings.ToLower(s.FromAddress), strings.ToLower(s.Username)}
for _, a := range m.Envelope.To {
skip = append(skip, strings.ToLower(a.Address()))
}
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, booking: true, subject: m.Envelope.Subject, skip: skip,
id: m.Envelope.MessageId, date: m.Envelope.Date})
}
continue
}
if isBounce(fromAddr, h.Get("Content-Type")) {
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, bounce: true, id: m.Envelope.MessageId, date: m.Envelope.Date})
}
continue
}
msg, err := match(d, append(msgIDs(m.Envelope.InReplyTo), msgIDs(h.Get("References"))...), fromAddr)
if err != nil {
return err
}
if msg == nil {
continue
}
if isAuto(h, m.Envelope.Subject) {
res.AutoReplies++
continue
}
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, msg: msg, id: m.Envelope.MessageId, date: m.Envelope.Date})
}
}
for _, f := range todo {
raw, err := fetchRaw(c, f.uid)
if err != nil {
return err
}
if f.booking {
if err := booked(d, f, raw, res); err != nil {
return err
}
continue
}
if f.bounce {
if err := bounced(d, raw, res); err != nil {
return err
}
continue
}
if err := replied(d, f, raw, res); err != nil {
return err
}
}
return nil
}
func fetchRaw(c *client.Client, uid uint32) ([]byte, error) {
set := new(imap.SeqSet)
set.AddNum(uid)
ch := make(chan *imap.Message, 1)
if err := c.UidFetch(set, []imap.FetchItem{fullSection.FetchItem()}, ch); err != nil {
return nil, err
}
for m := range ch {
if lit := m.GetBody(fullSection); lit != nil {
return io.ReadAll(io.LimitReader(lit, 6<<20))
}
}
return nil, nil
}
var msgIDRe = regexp.MustCompile(`<[^<>\s]+>`)
func msgIDs(s string) []string { return msgIDRe.FindAllString(s, -1) }
// match finds the sent email a message answers: by the Message-IDs it
// quotes, or else the latest email sent to its sender.
func match(d *db.DB, ids []string, fromAddr string) (*Message, error) {
var id int64
for _, mid := range ids {
if !strings.HasPrefix(mid, "<sm-") {
continue
}
err := d.QueryRow(`SELECT id FROM outreach WHERE message_id = ?`, mid).Scan(&id)
if err == nil {
return Get(d, id)
}
}
if fromAddr == "" {
return nil, nil
}
err := d.QueryRow(`SELECT id FROM outreach WHERE to_addr = ? AND status = 'sent' AND channel = 'email'
ORDER BY sent_at DESC LIMIT 1`, fromAddr).Scan(&id)
if err != nil {
return nil, nil
}
return Get(d, id)
}
func isBounce(fromAddr, contentType string) bool {
local, _, _ := strings.Cut(fromAddr, "@")
return local == "mailer-daemon" || local == "postmaster" ||
strings.Contains(strings.ToLower(contentType), "report-type=delivery-status")
}
var autoSubject = regexp.MustCompile(`(?i)^(auto(matic)?[ -]?(reply|response)|out of (the )?office|abwesenheit|absence|away|r[ée]ponse automatique)\b`)
func isAuto(h mail.Header, subject string) bool {
if a := strings.ToLower(strings.TrimSpace(h.Get("Auto-Submitted"))); a != "" && a != "no" {
return true
}
if h.Get("X-Autoreply") != "" || h.Get("X-Autorespond") != "" {
return true
}
if p := strings.ToLower(h.Get("Precedence")); p == "auto_reply" {
return true
}
return autoSubject.MatchString(strings.TrimSpace(subject))
}
// replied records a reply, and a request to stop.
func replied(d *db.DB, f found, raw []byte, res *Check) error {
text := replyText(raw)
at := f.date
if at.IsZero() {
at = time.Now()
}
ext := "reply:" + f.id
if f.id == "" {
ext = "reply:uid:" + strconv.FormatUint(uint64(f.uid), 10)
}
if f.msg.RepliedAt.IsZero() {
if err := MarkReplied(d, f.msg.ID, text, ext, at); err != nil {
return err
}
res.Replies++
}
if WantsStop(text) {
res.Stops++
return prospects.Suppress(d, "email", f.msg.To, "replied asking not to be contacted", at)
}
return nil
}
// bounced marks the email a delivery report is about as bounced, and its
// address as one that bounces.
func bounced(d *db.DB, raw []byte, res *Check) error {
for _, mid := range msgIDs(string(raw)) {
if !strings.HasPrefix(mid, "<sm-") {
continue
}
var id, contact int64
var to string
err := d.QueryRow(`SELECT id, contact_id, to_addr FROM outreach WHERE message_id = ?`, mid).Scan(&id, &contact, &to)
if err != nil {
continue
}
if _, err := d.Exec(`UPDATE outreach SET status = 'bounced', error = ? WHERE id = ? AND status = 'sent'`,
"The address bounced: "+bounceReason(raw), id); err != nil {
return err
}
if _, err := d.Exec(`UPDATE prospect_contacts SET email_status = ? WHERE id = ? AND email = ?`,
prospects.EmailInvalid, contact, to); err != nil {
return err
}
res.Bounces++
return nil
}
return nil
}
var (
diagRe = regexp.MustCompile(`(?im)^Diagnostic-Code:\s*(?:smtp;\s*)?(.+)$`)
statusRe = regexp.MustCompile(`(?im)^Status:\s*(.+)$`)
)
func bounceReason(raw []byte) string {
for _, re := range []*regexp.Regexp{diagRe, statusRe} {
if m := re.FindSubmatch(raw); m != nil {
return truncate(strings.TrimSpace(string(m[1])), 200)
}
}
return "the mail server reported it undeliverable"
}
// replyText is the start of what the person wrote, without the quoted
// message under it.
func replyText(raw []byte) string {
text := plainText(raw)
var out []string
for _, line := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") {
t := strings.TrimSpace(line)
if strings.HasPrefix(t, ">") {
continue
}
if quoteStart.MatchString(t) {
break
}
out = append(out, line)
}
return truncate(strings.TrimSpace(strings.Join(out, "\n")), 1000)
}
var quoteStart = regexp.MustCompile(`(?i)^(on .+ wrote:?|le .+ a écrit ?:|am .+ schrieb .+:|-+ ?original message ?-+|-+ ?forwarded message ?-+|from: .+|_{10,})$`)
// plainText is a message's text part (or its HTML, with the tags taken
// out).
func plainText(raw []byte) string {
r, err := gomail.CreateReader(bytes.NewReader(raw))
if err != nil {
return ""
}
var html string
for {
p, err := r.NextPart()
if err != nil {
break
}
h, ok := p.Header.(*gomail.InlineHeader)
if !ok {
continue
}
t, _, _ := h.ContentType()
b, _ := io.ReadAll(io.LimitReader(p.Body, 1<<20))
switch t {
case "text/plain", "":
return string(b)
case "text/html":
if html == "" {
html = stripTags(string(b))
}
}
}
return html
}
var (
tagRe = regexp.MustCompile(`(?s)<(style|script)[^>]*>.*?</(style|script)>|<[^>]+>`)
blankRe = regexp.MustCompile(`\n\s*\n+`)
)
func stripTags(s string) string {
s = strings.NewReplacer("<br>", "\n", "<br/>", "\n", "<br />", "\n", "</p>", "\n\n", "</div>", "\n").Replace(s)
s = tagRe.ReplaceAllString(s, "")
s = strings.NewReplacer("&nbsp;", " ", "&amp;", "&", "&lt;", "<", "&gt;", ">", "&quot;", `"`, "&#39;", "'").Replace(s)
return blankRe.ReplaceAllString(s, "\n\n")
}
var (
stopAlone = regexp.MustCompile(`(?i)^\W*(stop|unsubscribe|remove( me)?|opt[ -]?out)\W*$`)
stopPhrases = regexp.MustCompile(`(?i)\b(unsubscribe|remove me|take me off|opt me out|opt out|do not (contact|email|write)|don'?t (contact|email|write)|stop (emailing|contacting|writing|sending)|no more emails)\b`)
)
// WantsStop reports whether a reply asks not to be contacted again.
func WantsStop(reply string) bool {
reply = strings.TrimSpace(reply)
first, _, _ := strings.Cut(reply, "\n")
return stopAlone.MatchString(strings.TrimSpace(first)) || stopPhrases.MatchString(reply)
}
// bookingDays is how far back bookings are looked for the first time.
const bookingDays = 30
var (
emailRe = regexp.MustCompile(`[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`)
notNewBooking = regexp.MustCompile(`(?i)cancel|reschedul|declined|rejected|reminder|request`)
)
// booked records a Cal.com booking notice as a Booked step for the person
// who booked: the first address in it that isn't ours or Cal.com's. Notices
// of cancellations, reschedules and reminders are skipped.
func booked(d *db.DB, f found, raw []byte, res *Check) error {
if notNewBooking.MatchString(f.subject) {
return nil
}
text := plainText(raw)
attendee := ""
for _, a := range emailRe.FindAllString(text, -1) {
a = strings.ToLower(strings.Trim(a, ".'"))
local, _, _ := strings.Cut(a, "@")
if local == "noreply" || local == "no-reply" || local == "notifications" || contains(f.skip, a) {
continue
}
attendee = a
break
}
if attendee == "" {
return nil
}
at := f.date
if at.IsZero() {
at = time.Now()
}
ev := signals.Event{Stage: signals.StageBooked, Channel: "website", Email: attendee, Source: signals.SourceSupermarket,
ExternalID: "booking:" + f.id, Note: truncate(strings.TrimSpace(f.subject), 200), At: at}
if f.id == "" {
ev.ExternalID = "booking:" + attendee + ":" + at.UTC().Format("2006-01-02T15")
}
var id, sig int64
if err := d.QueryRow(`SELECT p.id, coalesce(p.signal_id, c.signal_id, 0) FROM prospect_contacts p
LEFT JOIN prospect_companies c ON c.id = p.company_id WHERE p.email = ? LIMIT 1`, attendee).Scan(&id, &sig); err == nil {
ev.Subject, ev.SignalID = prospects.Subject("contact", id), sig
var ch string
if d.QueryRow(`SELECT channel FROM outreach WHERE contact_id = ? AND status = 'sent' ORDER BY sent_at DESC LIMIT 1`, id).Scan(&ch) == nil {
ev.Channel = ch
}
} else {
ev.Subject = "booking:" + attendee
}
added, err := signals.Record(d, ev)
if added {
res.Bookings++
}
return err
}
func contains(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}