Drafts are written by the AI from the person's buying signal (hypothesis and angle), their company and their history, then reviewed and edited. Queued emails go out through the Core's mail server one at a time, within the sending hours, the daily limit and a gap, never to a suppressed or bouncing address or someone emailed in the last 14 days; with a signature, an opt-out line, UTM-tagged links and a copy in Sent. The inbox is read read-only every 10 minutes: replies (by Message-ID or sender) count as Replied, bounces mark the address, and "stop" replies are suppressed. LinkedIn messages are copied, sent by hand and marked sent. New pages: Prospects → Outreach and Settings → Email (with an SMTP, IMAP, SPF, DKIM and DMARC check). Schema 10; emersion/go-imap for IMAP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
520 lines
14 KiB
Go
520 lines
14 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"
|
|
)
|
|
|
|
// 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"`
|
|
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
|
|
}
|
|
if !first.Valid {
|
|
// Nothing sent yet: 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 {
|
|
since, _ := time.Parse(timeFormat, first.String)
|
|
criteria.Since = since.AddDate(0, 0, -1)
|
|
}
|
|
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, 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
|
|
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, 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 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.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(" ", " ", "&", "&", "<", "<", ">", ">", """, `"`, "'", "'").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)
|
|
}
|