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, "") { 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)[^>]*>.*?|<[^>]+>`) blankRe = regexp.MustCompile(`\n\s*\n+`) ) func stripTags(s string) string { s = strings.NewReplacer("
", "\n", "
", "\n", "
", "\n", "

", "\n\n", "", "\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) }