Phase 2 part 6: outreach by email and LinkedIn
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>
This commit is contained in:
@@ -0,0 +1,437 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/outreach"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
var mailPassword = secretField{"mail", secrets.MailPassword, "Password",
|
||||
"The mailbox's password, or an app password if your mail server has them.", ""}
|
||||
|
||||
// outreachSettings are the saved email settings, or the defaults.
|
||||
func (s *Server) outreachSettings() (outreach.Settings, bool) {
|
||||
p, _ := profile.Load(s.DB)
|
||||
set, ok, err := outreach.Load(s.DB, s.Core, p)
|
||||
if err != nil {
|
||||
s.Log.Error("loading the email settings", "err", err)
|
||||
}
|
||||
return set, ok
|
||||
}
|
||||
|
||||
// mailbox is the sender for the saved settings, or why there's none.
|
||||
func (s *Server) mailbox() (outreach.Settings, outreach.Mailbox, error) {
|
||||
set, ok := s.outreachSettings()
|
||||
pw := s.Secrets.Get(secrets.MailPassword)
|
||||
if !ok {
|
||||
return set, outreach.Mailbox{}, errors.New("set up email first, under Settings → Email")
|
||||
}
|
||||
if err := set.Ready(pw); err != nil {
|
||||
return set, outreach.Mailbox{}, err
|
||||
}
|
||||
return set, outreach.Mailbox{Settings: set, Password: pw}, nil
|
||||
}
|
||||
|
||||
// outreachDrafts is how many drafts wait, for the menu.
|
||||
func (s *Server) outreachDrafts() int {
|
||||
counts, err := outreach.Counts(s.DB)
|
||||
if err != nil {
|
||||
s.Log.Error("counting outreach", "err", err)
|
||||
}
|
||||
return counts[outreach.StatusDraft]
|
||||
}
|
||||
|
||||
// --- Settings → Email ---
|
||||
|
||||
func (s *Server) emailPage(w http.ResponseWriter, r *http.Request) {
|
||||
set, _ := s.outreachSettings()
|
||||
s.renderEmail(w, r, set, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderEmail(w http.ResponseWriter, r *http.Request, set outreach.Settings, errMsg string) {
|
||||
s.render(w, r, "email", page{Title: "Email", Nav: "settings/email", Error: errMsg, Data: map[string]any{
|
||||
"S": set,
|
||||
"Password": mailPassword,
|
||||
"Set": s.Secrets.Has(secrets.MailPassword),
|
||||
"Hours": hours(),
|
||||
}})
|
||||
}
|
||||
|
||||
func hours() []int {
|
||||
h := make([]int, 25)
|
||||
for i := range h {
|
||||
h[i] = i
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func (s *Server) emailSave(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
f := r.PostFormValue
|
||||
num := func(k string) int { n, _ := strconv.Atoi(strings.TrimSpace(f(k))); return n }
|
||||
set := outreach.Settings{
|
||||
SMTPHost: f("smtp_host"), SMTPPort: num("smtp_port"), IMAPHost: f("imap_host"), IMAPPort: num("imap_port"),
|
||||
Username: f("username"), FromName: f("from_name"), FromAddress: f("from_address"),
|
||||
DailyLimit: num("daily_limit"), GapMinutes: num("gap_minutes"), StartHour: num("start_hour"), EndHour: num("end_hour"),
|
||||
Weekends: f("weekends") == "on", Footer: strings.TrimSpace(strings.ReplaceAll(f("footer"), "\r\n", "\n")),
|
||||
SchedulingLink: f("scheduling_link"), SaveToSent: f("save_to_sent") == "on", ReadReplies: f("read_replies") == "on",
|
||||
}
|
||||
if err := outreach.Save(s.DB, set); err != nil {
|
||||
s.renderEmail(w, r, set, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.saveSecrets(r, []secretField{mailPassword}); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/settings/email", "saved")
|
||||
}
|
||||
|
||||
// emailTest signs in to the mail server and the mailbox, and looks up the
|
||||
// domain's mail records. Nothing is sent.
|
||||
func (s *Server) emailTest(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
||||
defer cancel()
|
||||
set, _ := s.outreachSettings()
|
||||
pw := s.Secrets.Get(secrets.MailPassword)
|
||||
type line struct {
|
||||
OK bool
|
||||
Text string
|
||||
}
|
||||
var lines []line
|
||||
if err := set.Ready(pw); err != nil {
|
||||
lines = append(lines, line{false, "Save the settings and password first: " + err.Error() + "."})
|
||||
} else {
|
||||
if err := outreach.CheckSMTP(ctx, set, pw); err != nil {
|
||||
lines = append(lines, line{false, "Sending: " + err.Error()})
|
||||
} else {
|
||||
lines = append(lines, line{true, "Sending: signed in to " + set.SMTPHost + "."})
|
||||
}
|
||||
if n, err := outreach.CheckIMAP(ctx, set, pw); err != nil {
|
||||
lines = append(lines, line{false, "Reading replies: " + err.Error()})
|
||||
} else {
|
||||
lines = append(lines, line{true, "Reading replies: opened the inbox (" + strconv.Itoa(int(n)) + " messages), read-only."})
|
||||
}
|
||||
}
|
||||
if dom := set.FromDomain(); dom != "" {
|
||||
c := outreach.CheckDNS(ctx, dom)
|
||||
lines = append(lines,
|
||||
line{c.SPF != "", "SPF for " + dom + ": " + or(c.SPF, "none found. Without it, many servers treat your email as suspect.")},
|
||||
line{c.DKIMSelector != "", "DKIM: " + or(dkimText(c.DKIMSelector), "no key found at the usual names; check with whoever runs your mail server that outgoing mail is signed.")},
|
||||
line{c.DMARC != "", "DMARC: " + or(c.DMARC, "none found. Add a DMARC record (start with p=none) so receivers trust your domain.")},
|
||||
)
|
||||
}
|
||||
s.fragment(w, "email", "email-test", lines)
|
||||
}
|
||||
|
||||
func or(a, b string) string {
|
||||
if a != "" {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func dkimText(sel string) string {
|
||||
if sel == "" {
|
||||
return ""
|
||||
}
|
||||
return "a key is published (selector “" + sel + "”)."
|
||||
}
|
||||
|
||||
func (s *Server) emailSendTest(w http.ResponseWriter, r *http.Request) {
|
||||
set, mb, err := s.mailbox()
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
||||
defer cancel()
|
||||
err = outreach.SendTest(ctx, set, mb, time.Now())
|
||||
}
|
||||
if err != nil {
|
||||
s.renderEmail(w, r, set, "The test email didn't go: "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/settings/email", "test-sent")
|
||||
}
|
||||
|
||||
// --- The outreach page ---
|
||||
|
||||
func outreachTab(v string) string {
|
||||
for _, t := range outreach.Tabs {
|
||||
if v == t.ID {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return outreach.StatusDraft
|
||||
}
|
||||
|
||||
func (s *Server) outreachPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderOutreach(w, r, outreachTab(r.URL.Query().Get("tab")), "")
|
||||
}
|
||||
|
||||
func (s *Server) renderOutreach(w http.ResponseWriter, r *http.Request, tab, errMsg string) {
|
||||
msgs, err := outreach.List(s.DB, tab, 200)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
counts, err := outreach.Counts(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
set, ok := s.outreachSettings()
|
||||
_, _, notReady := s.mailbox()
|
||||
today, _ := outreach.SentToday(s.DB, time.Now())
|
||||
last, _ := outreach.LastCheck(s.DB)
|
||||
list, _ := signals.List(s.DB)
|
||||
names := map[int64]string{}
|
||||
for _, sg := range list {
|
||||
names[sg.ID] = sg.Name
|
||||
}
|
||||
emailable, _ := outreach.Candidates(s.DB, 0, outreach.ChannelEmail, 1000)
|
||||
linkable, _ := outreach.Candidates(s.DB, 0, outreach.ChannelLinkedIn, 1000)
|
||||
var window string
|
||||
if err := set.Window(time.Now()); err != nil {
|
||||
window = err.Error()
|
||||
}
|
||||
s.render(w, r, "outreach", page{Title: "Outreach", Nav: "prospects/outreach", Error: errMsg, Data: map[string]any{
|
||||
"Tab": tab,
|
||||
"Tabs": outreach.Tabs,
|
||||
"Counts": counts,
|
||||
"Messages": msgs,
|
||||
"S": set,
|
||||
"Configured": ok,
|
||||
"NotReady": notReady,
|
||||
"SentToday": today,
|
||||
"Window": window,
|
||||
"LastCheck": last,
|
||||
"Signals": list,
|
||||
"SignalNames": names,
|
||||
"Emailable": len(emailable),
|
||||
"Linkable": len(linkable),
|
||||
"Limit": outreach.LinkedInLimit,
|
||||
}})
|
||||
}
|
||||
|
||||
// newAIClient is ai.New; tests replace it.
|
||||
var newAIClient = ai.New
|
||||
|
||||
// draftClient is the AI client and profile for drafting.
|
||||
func (s *Server) draftClient() (ai.Client, *profile.Profile, error) {
|
||||
p, err := profile.Load(s.DB)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cfg, err := ai.LoadConfig(s.DB)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
c, err := newAIClient(cfg, s.Secrets)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("drafting needs the AI: choose a provider under Settings → AI")
|
||||
}
|
||||
return c, p, nil
|
||||
}
|
||||
|
||||
// outreachDraft writes one message, from the review screen.
|
||||
func (s *Server) outreachDraft(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id, _ := strconv.ParseInt(r.PostFormValue("contact"), 10, 64)
|
||||
channel := r.PostFormValue("channel")
|
||||
tab := reviewTab(r.PostFormValue("tab"))
|
||||
filter, _ := strconv.ParseInt(r.PostFormValue("filter"), 10, 64)
|
||||
c, p, err := s.draftClient()
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
||||
defer cancel()
|
||||
set, _ := s.outreachSettings()
|
||||
var m *outreach.Message
|
||||
if m, err = outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err == nil {
|
||||
redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach")
|
||||
return
|
||||
}
|
||||
}
|
||||
if errors.Is(err, prospects.ErrNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.renderProspects(w, r, tab, filter, "Couldn't draft it: "+err.Error())
|
||||
}
|
||||
|
||||
// maxDraftMany is how many messages one click drafts.
|
||||
const maxDraftMany = 5
|
||||
|
||||
// outreachDraftMany drafts for accepted people who haven't been written to.
|
||||
func (s *Server) outreachDraftMany(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
|
||||
channel := r.PostFormValue("channel")
|
||||
if channel != outreach.ChannelLinkedIn {
|
||||
channel = outreach.ChannelEmail
|
||||
}
|
||||
c, p, err := s.draftClient()
|
||||
if err != nil {
|
||||
s.renderOutreach(w, r, outreach.StatusDraft, err.Error())
|
||||
return
|
||||
}
|
||||
ids, err := outreach.Candidates(s.DB, sig, channel, maxDraftMany)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
s.renderOutreach(w, r, outreach.StatusDraft, "Nobody to write to: accept people in Review first (with an email address, or a LinkedIn profile).")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Minute)
|
||||
defer cancel()
|
||||
set, _ := s.outreachSettings()
|
||||
var failed []string
|
||||
for _, id := range ids {
|
||||
if _, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil {
|
||||
failed = append(failed, err.Error())
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
s.renderOutreach(w, r, outreach.StatusDraft, "Some weren't drafted: "+strings.Join(failed, "; "))
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/outreach", "drafted-outreach")
|
||||
}
|
||||
|
||||
// outreachAction handles a message's buttons.
|
||||
func (s *Server) outreachAction(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
tab := outreachTab(r.PostFormValue("tab"))
|
||||
now := time.Now()
|
||||
var msg string
|
||||
switch r.PathValue("action") {
|
||||
case "save", "queue":
|
||||
if _, has := r.PostForm["body"]; has {
|
||||
err = outreach.Edit(s.DB, id, r.PostFormValue("subject"), r.PostFormValue("body"))
|
||||
}
|
||||
msg = "saved"
|
||||
if err == nil && r.PathValue("action") == "queue" {
|
||||
err, msg = outreach.Queue(s.DB, id, now), "queued"
|
||||
}
|
||||
case "unqueue":
|
||||
err, msg = outreach.Unqueue(s.DB, id), "unqueued"
|
||||
case "discard":
|
||||
err, msg = outreach.Discard(s.DB, id), "discarded"
|
||||
case "send-now":
|
||||
var set outreach.Settings
|
||||
var mb outreach.Mailbox
|
||||
if set, mb, err = s.mailbox(); err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
||||
s.sending.Lock()
|
||||
err = outreach.SendNow(ctx, s.DB, set, mb, s.tagger(), id, now)
|
||||
s.sending.Unlock()
|
||||
cancel()
|
||||
}
|
||||
msg = "sent"
|
||||
case "mark-sent":
|
||||
err, msg = outreach.MarkSent(s.DB, id, r.PostFormValue("body"), now), "marked-sent"
|
||||
case "replied":
|
||||
err, msg = outreach.MarkReplied(s.DB, id, r.PostFormValue("reply"), "", now), "reply-recorded"
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, outreach.ErrNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.renderOutreach(w, r, tab, "Couldn't do that: "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/outreach?tab="+tab+"#m-"+strconv.FormatInt(id, 10), msg)
|
||||
}
|
||||
|
||||
// outreachCheck reads the inbox now.
|
||||
func (s *Server) outreachCheck(w http.ResponseWriter, r *http.Request) {
|
||||
set, mb, err := s.mailbox()
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
||||
defer cancel()
|
||||
_, err = outreach.CheckReplies(ctx, s.DB, set, mb.Password, time.Now())
|
||||
}
|
||||
if err != nil {
|
||||
s.renderOutreach(w, r, outreachTab(r.PostFormValue("tab")), "Couldn't read the inbox: "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/outreach?tab=replied", "checked")
|
||||
}
|
||||
|
||||
// RunOutreach sends queued emails as their turn comes, and reads replies
|
||||
// every 10 minutes.
|
||||
func (s *Server) RunOutreach(ctx context.Context) {
|
||||
tick := time.NewTicker(time.Minute)
|
||||
defer tick.Stop()
|
||||
var lastCheck time.Time
|
||||
for {
|
||||
if set, mb, err := s.mailbox(); err == nil {
|
||||
s.sending.Lock()
|
||||
sctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
m, err := outreach.SendDue(sctx, s.DB, set, mb, s.tagger(), time.Now())
|
||||
cancel()
|
||||
s.sending.Unlock()
|
||||
if err != nil {
|
||||
s.Log.Warn("outreach: sending", "message", idOf(m), "err", err)
|
||||
} else if m != nil {
|
||||
s.Log.Info("outreach: sent", "message", m.ID, "to", m.To)
|
||||
}
|
||||
if set.ReadReplies && time.Since(lastCheck) >= 10*time.Minute {
|
||||
lastCheck = time.Now()
|
||||
cctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
if res, err := outreach.CheckReplies(cctx, s.DB, set, mb.Password, time.Now()); err != nil {
|
||||
s.Log.Warn("outreach: reading replies", "err", err)
|
||||
} else if res.Replies+res.Bounces > 0 {
|
||||
s.Log.Info("outreach: replies", "replies", res.Replies, "bounces", res.Bounces, "stops", res.Stops)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func idOf(m *outreach.Message) int64 {
|
||||
if m == nil {
|
||||
return 0
|
||||
}
|
||||
return m.ID
|
||||
}
|
||||
Reference in New Issue
Block a user