package outreach import ( "bytes" "context" "crypto/rand" "crypto/tls" "encoding/hex" "fmt" "mime" "mime/quotedprintable" "net" "net/mail" "net/smtp" "strconv" "strings" "time" ) // Email is a composed message, ready to send. type Email struct { From, To string MessageID string Raw []byte } // newMessageID makes a Message-ID that replies will quote back. func newMessageID(id int64, domain string) string { b := make([]byte, 8) _, _ = rand.Read(b) if domain == "" { domain = "supermarket.invalid" } return fmt.Sprintf("", id, hex.EncodeToString(b), domain) } // Compose builds a plain-text email with the footer under the text. func Compose(s Settings, toName, to, subject, body string, messageID string, now time.Time) *Email { var b bytes.Buffer h := func(k, v string) { b.WriteString(k + ": " + v + "\r\n") } h("From", (&mail.Address{Name: s.FromName, Address: s.FromAddress}).String()) h("To", (&mail.Address{Name: toName, Address: to}).String()) h("Subject", mime.QEncoding.Encode("utf-8", subject)) h("Date", now.Format(time.RFC1123Z)) h("Message-ID", messageID) h("MIME-Version", "1.0") h("Content-Type", "text/plain; charset=utf-8") h("Content-Transfer-Encoding", "quoted-printable") h("List-Unsubscribe", "") b.WriteString("\r\n") text := strings.TrimSpace(body) if f := strings.TrimSpace(s.Footer); f != "" { text += "\n\n-- \n" + f } text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n") + "\r\n" qp := quotedprintable.NewWriter(&b) _, _ = qp.Write([]byte(text)) _ = qp.Close() return &Email{From: s.FromAddress, To: to, MessageID: messageID, Raw: b.Bytes()} } // smtpClient connects and signs in to the mail server. func smtpClient(ctx context.Context, s Settings, password string) (*smtp.Client, error) { addr := net.JoinHostPort(s.SMTPHost, strconv.Itoa(s.SMTPPort)) dialer := &net.Dialer{Timeout: 30 * time.Second} tlsConf := &tls.Config{ServerName: s.SMTPHost} var conn net.Conn var err error if s.SMTPPort == 465 { conn, err = (&tls.Dialer{NetDialer: dialer, Config: tlsConf}).DialContext(ctx, "tcp", addr) } else { conn, err = dialer.DialContext(ctx, "tcp", addr) } if err != nil { return nil, fmt.Errorf("connecting to %s: %w", addr, err) } _ = conn.SetDeadline(time.Now().Add(2 * time.Minute)) c, err := smtp.NewClient(conn, s.SMTPHost) if err != nil { conn.Close() return nil, fmt.Errorf("%s: %w", addr, err) } if d := s.FromDomain(); d != "" { if err := c.Hello(d); err != nil { c.Close() return nil, err } } if s.SMTPPort != 465 { if ok, _ := c.Extension("STARTTLS"); ok { if err := c.StartTLS(tlsConf); err != nil { c.Close() return nil, fmt.Errorf("starting TLS with %s: %w", addr, err) } } else if !s.Insecure { c.Close() return nil, fmt.Errorf("%s doesn't offer STARTTLS; use port 465 or 587", addr) } } if err := c.Auth(smtp.PlainAuth("", s.Username, password, s.SMTPHost)); err != nil { c.Close() return nil, fmt.Errorf("signing in to %s as %s: %w", s.SMTPHost, s.Username, err) } return c, nil } // Send hands an email to the mail server. func Send(ctx context.Context, s Settings, password string, e *Email) error { c, err := smtpClient(ctx, s, password) if err != nil { return err } defer c.Close() if err := c.Mail(e.From); err != nil { return fmt.Errorf("the server refused the sender %s: %w", e.From, err) } if err := c.Rcpt(e.To); err != nil { return fmt.Errorf("the server refused the recipient %s: %w", e.To, err) } w, err := c.Data() if err != nil { return err } if _, err := w.Write(e.Raw); err != nil { return err } if err := w.Close(); err != nil { return fmt.Errorf("the server didn't accept the message: %w", err) } return c.Quit() } // CheckSMTP signs in to the mail server without sending anything. func CheckSMTP(ctx context.Context, s Settings, password string) error { c, err := smtpClient(ctx, s, password) if err != nil { return err } defer c.Close() return c.Quit() } // DNSCheck looks up the From domain's SPF, DMARC and (at common selectors) // DKIM records, which decide whether outreach lands in the inbox. type DNSCheck struct { Domain string SPF, DMARC string // the record, or "" DKIMSelector string // where a DKIM key was found, or "" } var dkimSelectors = []string{"default", "dkim", "mail", "s1", "selector1", "google", "k1"} // lookupTXT is net.DefaultResolver.LookupTXT; tests replace it. var lookupTXT = net.DefaultResolver.LookupTXT // CheckDNS looks up a domain's mail records. func CheckDNS(ctx context.Context, domain string) DNSCheck { out := DNSCheck{Domain: domain} find := func(name, prefix string) string { txts, err := lookupTXT(ctx, name) if err != nil { return "" } for _, t := range txts { l := strings.ToLower(strings.TrimSpace(t)) // "v=DKIM1" is optional in a DKIM record; its key ("p=") isn't. if strings.HasPrefix(l, prefix) || (prefix == "p=" && strings.Contains(l, "p=")) { return t } } return "" } out.SPF = find(domain, "v=spf1") out.DMARC = find("_dmarc."+domain, "v=dmarc1") for _, sel := range dkimSelectors { if find(sel+"._domainkey."+domain, "p=") != "" { out.DKIMSelector = sel break } } return out }