// Package mail sends the platform's own emails (document published, new // findings) through an SMTP relay (Strato in production), rendered from // embedded German and English templates with the BreakPilot layout. package mail import ( "bytes" "context" "crypto/rand" "crypto/tls" "encoding/hex" "errors" "fmt" "mime" "mime/quotedprintable" "net" "net/smtp" "strings" "sync" "time" ) // Message is one email to one recipient. type Message struct { To string Subject string Text string HTML string } // Sender delivers a Message. type Sender interface { Send(ctx context.Context, m Message) error } // Config of the SMTP relay. type Config struct { Host string // smtp.strato.de Port int // 587 (STARTTLS) or 465 (implicit TLS) User string Password string From string // noreply@breakpilot.com FromName string // BreakPilot } // Configured reports whether mail can be sent. func (c Config) Configured() bool { return c.Host != "" && c.From != "" } // SMTP sends through a relay with STARTTLS (or implicit TLS on 465). type SMTP struct { Cfg Config Timeout time.Duration } func (s *SMTP) Send(ctx context.Context, m Message) error { timeout := s.Timeout if timeout <= 0 { timeout = 30 * time.Second } addr := net.JoinHostPort(s.Cfg.Host, fmt.Sprint(s.Cfg.Port)) d := net.Dialer{Timeout: timeout} var conn net.Conn var err error tlsCfg := &tls.Config{ServerName: s.Cfg.Host, MinVersion: tls.VersionTLS12} if s.Cfg.Port == 465 { conn, err = tls.DialWithDialer(&d, "tcp", addr, tlsCfg) } else { conn, err = d.DialContext(ctx, "tcp", addr) } if err != nil { return fmt.Errorf("mail: dial %s: %w", addr, err) } _ = conn.SetDeadline(time.Now().Add(timeout)) c, err := smtp.NewClient(conn, s.Cfg.Host) if err != nil { _ = conn.Close() return fmt.Errorf("mail: hello: %w", err) } defer func() { _ = c.Close() }() if s.Cfg.Port != 465 { if ok, _ := c.Extension("STARTTLS"); !ok { return errors.New("mail: relay does not offer STARTTLS") } if err := c.StartTLS(tlsCfg); err != nil { return fmt.Errorf("mail: starttls: %w", err) } } if s.Cfg.User != "" { if err := c.Auth(smtp.PlainAuth("", s.Cfg.User, s.Cfg.Password, s.Cfg.Host)); err != nil { return fmt.Errorf("mail: auth: %w", err) } } if err := c.Mail(s.Cfg.From); err != nil { return fmt.Errorf("mail: from: %w", err) } if err := c.Rcpt(m.To); err != nil { return fmt.Errorf("mail: rcpt: %w", err) } w, err := c.Data() if err != nil { return fmt.Errorf("mail: data: %w", err) } if _, err := w.Write(Build(m, s.Cfg, time.Now())); err != nil { return fmt.Errorf("mail: write: %w", err) } if err := w.Close(); err != nil { return fmt.Errorf("mail: send: %w", err) } return c.Quit() } // Build renders the RFC 5322 message: multipart/alternative with a text and // an HTML part, both UTF-8 quoted-printable. func Build(m Message, cfg Config, now time.Time) []byte { boundary := "bp-" + randomHex(12) domain := "breakpilot.com" if i := strings.LastIndex(cfg.From, "@"); i >= 0 { domain = cfg.From[i+1:] } from := cfg.From if cfg.FromName != "" { from = mime.QEncoding.Encode("utf-8", cfg.FromName) + " <" + cfg.From + ">" } var b bytes.Buffer h := func(k, v string) { fmt.Fprintf(&b, "%s: %s\r\n", k, v) } h("From", from) h("To", m.To) h("Subject", mime.QEncoding.Encode("utf-8", m.Subject)) h("Date", now.UTC().Format(time.RFC1123Z)) h("Message-ID", "<"+randomHex(16)+"@"+domain+">") h("MIME-Version", "1.0") h("Auto-Submitted", "auto-generated") h("Content-Type", `multipart/alternative; boundary="`+boundary+`"`) b.WriteString("\r\n") part := func(ctype, body string) { fmt.Fprintf(&b, "--%s\r\nContent-Type: %s; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n", boundary, ctype) qp := quotedprintable.NewWriter(&b) _, _ = qp.Write([]byte(strings.ReplaceAll(body, "\n", "\r\n"))) _ = qp.Close() b.WriteString("\r\n") } part("text/plain", m.Text) if m.HTML != "" { part("text/html", m.HTML) } fmt.Fprintf(&b, "--%s--\r\n", boundary) return b.Bytes() } func randomHex(n int) string { buf := make([]byte, n) _, _ = rand.Read(buf) return hex.EncodeToString(buf) } // Recorder is a Sender for tests and for environments without a relay. type Recorder struct { mu sync.Mutex Sent []Message Fail error } func (r *Recorder) Send(_ context.Context, m Message) error { r.mu.Lock() defer r.mu.Unlock() if r.Fail != nil { return r.Fail } r.Sent = append(r.Sent, m) return nil } // Messages returns a copy of what was sent. func (r *Recorder) Messages() []Message { r.mu.Lock() defer r.mu.Unlock() return append([]Message(nil), r.Sent...) }