// SPDX-License-Identifier: AGPL-3.0-or-later package mail import ( "bytes" "context" "crypto/rand" "crypto/tls" "encoding/hex" "errors" "fmt" "mime" "mime/multipart" "mime/quotedprintable" "net" "net/mail" "net/smtp" "net/textproto" "strconv" "strings" "time" ) // Config is the mail server and sender. PocketBase holds the same values for // its own auth emails; settings.Service.MailConfig reads them from there. type Config struct { Enabled bool Host string Port int Username string Password string // TLS connects with implicit TLS (usually port 465). Without it the // connection is upgraded with STARTTLS when the server offers it, as // PocketBase does. TLS bool SenderName string SenderAddress string } // ErrNotConfigured is returned when no mail server is set up. var ErrNotConfigured = errors.New("mail: no mail server is configured") // DeliveryError is the mail server refusing the message or the connection. type DeliveryError struct{ Err error } func (e *DeliveryError) Error() string { return "mail: " + e.Err.Error() } func (e *DeliveryError) Unwrap() error { return e.Err } // SMTPSender delivers messages to the mail server Config returns, read on // every send so admin panel changes apply at once. type SMTPSender struct { Config func(ctx context.Context) (Config, error) // Timeout bounds one delivery; zero means 30 seconds. Timeout time.Duration } func (s *SMTPSender) Send(ctx context.Context, m Message) error { cfg, err := s.Config(ctx) if err != nil { return err } if !cfg.Enabled || cfg.Host == "" { return ErrNotConfigured } from, err := mail.ParseAddress(cfg.SenderAddress) if err != nil { return &DeliveryError{Err: fmt.Errorf("sender address %q: %w", cfg.SenderAddress, err)} } from.Name = cfg.SenderName to, err := mail.ParseAddress(m.To) if err != nil { return &DeliveryError{Err: fmt.Errorf("recipient %q: %w", m.To, err)} } body, err := build(from, to, m) if err != nil { return err } timeout := s.Timeout if timeout == 0 { timeout = 30 * time.Second } ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() if err := deliver(ctx, cfg, from.Address, to.Address, body); err != nil { return &DeliveryError{Err: err} } return nil } func deliver(ctx context.Context, cfg Config, from, to string, body []byte) error { port := cfg.Port if port == 0 { port = 587 } addr := net.JoinHostPort(cfg.Host, strconv.Itoa(port)) tlsConfig := &tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12} var dialer net.Dialer conn, err := dialer.DialContext(ctx, "tcp", addr) if err != nil { return err } if deadline, ok := ctx.Deadline(); ok { _ = conn.SetDeadline(deadline) } if cfg.TLS { tlsConn := tls.Client(conn, tlsConfig) if err := tlsConn.HandshakeContext(ctx); err != nil { conn.Close() return err } conn = tlsConn } c, err := smtp.NewClient(conn, cfg.Host) if err != nil { conn.Close() return err } defer c.Close() if !cfg.TLS { if ok, _ := c.Extension("STARTTLS"); ok { if err := c.StartTLS(tlsConfig); err != nil { return err } } } if cfg.Username != "" { if ok, _ := c.Extension("AUTH"); !ok { return errors.New("the server does not accept a login (no AUTH)") } if err := c.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil { return err } } if err := c.Mail(from); err != nil { return err } if err := c.Rcpt(to); err != nil { return err } w, err := c.Data() if err != nil { return err } if _, err := w.Write(body); err != nil { w.Close() return err } if err := w.Close(); err != nil { return err } return c.Quit() } // build renders m as a multipart/alternative message. func build(from, to *mail.Address, m Message) ([]byte, error) { var buf bytes.Buffer mw := multipart.NewWriter(&buf) domain := "docwell.localhost" if at := strings.LastIndexByte(from.Address, '@'); at >= 0 { domain = from.Address[at+1:] } id := make([]byte, 16) _, _ = rand.Read(id) header := []string{ "From: " + from.String(), "To: " + to.String(), "Subject: " + mime.QEncoding.Encode("utf-8", m.Subject), "Date: " + time.Now().UTC().Format(time.RFC1123Z), "Message-ID: <" + hex.EncodeToString(id) + "@" + domain + ">", "MIME-Version: 1.0", "Content-Type: multipart/alternative; boundary=" + mw.Boundary(), } var out bytes.Buffer out.WriteString(strings.Join(header, "\r\n") + "\r\n\r\n") for _, part := range []struct{ kind, body string }{{"text/plain", m.Text}, {"text/html", m.HTML}} { if part.body == "" { continue } pw, err := mw.CreatePart(textproto.MIMEHeader{ "Content-Type": {part.kind + "; charset=utf-8"}, "Content-Transfer-Encoding": {"quoted-printable"}, }) if err != nil { return nil, err } qp := quotedprintable.NewWriter(pw) if _, err := qp.Write([]byte(part.body)); err != nil { return nil, err } if err := qp.Close(); err != nil { return nil, err } } if err := mw.Close(); err != nil { return nil, err } out.Write(buf.Bytes()) return out.Bytes(), nil }