Files
tenant-registry/internal/mail/mail.go
T
sharang 69c15be333
ci / shared (push) Successful in 12s
ci / test (push) Successful in 9m8s
ci / image (push) Successful in 36s
feat(onprem): APP_ENV=onprem with directory users and installation mail (#146)
2026-11-20 16:31:11 +00:00

234 lines
6.3 KiB
Go

// 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/base64"
"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
Attachments []Attachment
}
// Attachment is a file sent with the message (base64 in the mail).
type Attachment struct {
Name string // file name shown to the recipient
ContentType string // e.g. application/pdf
Data []byte
}
// 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
// TLS: "starttls", "tls" (implicit) or "none" (plain internal relay, no
// AUTH). Empty: "tls" on port 465, else "starttls".
TLS string
}
func (c Config) tlsMode() string {
switch {
case c.TLS != "":
return c.TLS
case c.Port == 465:
return "tls"
}
return "starttls"
}
// Configured reports whether mail can be sent.
func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
// SMTP sends through a relay with STARTTLS, implicit TLS, or (TLS "none",
// on-prem relays inside the customer's network) in plain text.
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}
mode := s.Cfg.tlsMode()
if mode == "tls" {
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 mode == "starttls" {
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 mode == "none" {
return errors.New("mail: no AUTH over an unencrypted connection")
}
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. With attachments the
// alternative part is wrapped in multipart/mixed, followed by one base64
// part per attachment.
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")
mixed := ""
if len(m.Attachments) > 0 {
mixed = "bp-mixed-" + randomHex(12)
h("Content-Type", `multipart/mixed; boundary="`+mixed+`"`)
b.WriteString("\r\n")
fmt.Fprintf(&b, "--%s\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", mixed, boundary)
} else {
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)
if mixed == "" {
return b.Bytes()
}
for _, a := range m.Attachments {
ctype := a.ContentType
if ctype == "" {
ctype = "application/octet-stream"
}
name := mime.QEncoding.Encode("utf-8", a.Name)
fmt.Fprintf(&b, "\r\n--%s\r\nContent-Type: %s; name=\"%s\"\r\nContent-Disposition: attachment; filename=\"%s\"\r\nContent-Transfer-Encoding: base64\r\n\r\n", mixed, ctype, name, name)
enc := base64.StdEncoding.EncodeToString(a.Data)
for len(enc) > 76 {
b.WriteString(enc[:76] + "\r\n")
enc = enc[76:]
}
b.WriteString(enc + "\r\n")
}
fmt.Fprintf(&b, "--%s--\r\n", mixed)
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...)
}