1// Package smtpclient is an SMTP client, for submitting to an SMTP server or
2// delivering from a queue.
4// Email clients can submit a message to SMTP server, after which the server is
5// responsible for delivery to the final destination. A submission client
6// typically connects with TLS, and PKIX-verifies the server's certificate. The
7// client then authenticates using a SASL mechanism.
9// Email servers manage a message queue, from which they will try to deliver
10// messages. In case of temporary failures, the message is kept in the queue and
11// tried again later. For delivery, no authentication is done. TLS is opportunistic
12// by default (TLS certificates not verified), but TLS and certificate verification
13// can be opted into by domains by specifying an MTA-STS policy for the domain, or
14// DANE TLSA records for their MX hosts.
16// Delivering a message from a queue would involve:
17// 1. Looking up an MTA-STS policy, through a cache.
18// 2. Resolving the MX targets for a domain, through smtpclient.GatherDestinations,
19// and for each destination try delivery through:
20// 3. Looking up IP addresses for the destination, with smtpclient.GatherIPs.
21// 4. Looking up TLSA records for DANE, in case of authentic DNS responses
22// (DNSSEC), with smtpclient.GatherTLSA.
23// 5. Dialing the MX target with smtpclient.Dial.
24// 6. Initializing a SMTP session with smtpclient.New, with proper TLS
25// configuration based on discovered MTA-STS and DANE policies, and finally calling
46 "github.com/mjl-/adns"
48 "github.com/mjl-/mox/dane"
49 "github.com/mjl-/mox/dns"
50 "github.com/mjl-/mox/mlog"
51 "github.com/mjl-/mox/moxio"
52 "github.com/mjl-/mox/sasl"
53 "github.com/mjl-/mox/smtp"
54 "github.com/mjl-/mox/stub"
55 "github.com/mjl-/mox/tlsrpt"
58// todo future: add function to deliver message to multiple recipients. requires more elaborate return value, indicating success per message: some recipients may succeed, others may fail, and we should still deliver. to prevent backscatter, we also sometimes don't allow multiple recipients.
../rfc/5321:1144
61 MetricCommands stub.HistogramVec = stub.HistogramVecIgnore{}
62 MetricTLSRequiredNoIgnored stub.CounterVec = stub.CounterVecIgnore{}
63 MetricPanicInc = func() {}
67 ErrSize = errors.New("message too large for remote smtp server") // SMTP server announced a maximum message size and the message to be delivered exceeds it.
68 Err8bitmimeUnsupported = errors.New("remote smtp server does not implement 8bitmime extension, required by message")
69 ErrSMTPUTF8Unsupported = errors.New("remote smtp server does not implement smtputf8 extension, required by message")
70 ErrRequireTLSUnsupported = errors.New("remote smtp server does not implement requiretls extension, required for delivery")
71 ErrStatus = errors.New("remote smtp server sent unexpected response status code") // Relatively common, e.g. when a 250 OK was expected and server sent 451 temporary error.
72 ErrProtocol = errors.New("smtp protocol error") // After a malformed SMTP response or inconsistent multi-line response.
73 ErrTLS = errors.New("tls error") // E.g. handshake failure, or hostname verification was required and failed.
74 ErrBotched = errors.New("smtp connection is botched") // Set on a client, and returned for new operations, after an i/o error or malformed SMTP response.
75 ErrClosed = errors.New("client is closed")
78// TLSMode indicates if TLS must, should or must not be used.
82 // TLS immediately ("implicit TLS"), directly starting TLS on the TCP connection,
83 // so not using STARTTLS. Whether PKIX and/or DANE is verified is specified
85 TLSImmediate TLSMode = "immediate"
87 // Required TLS with STARTTLS for SMTP servers. The STARTTLS command is always
88 // executed, even if the server does not announce support.
89 // Whether PKIX and/or DANE is verified is specified separately.
90 TLSRequiredStartTLS TLSMode = "requiredstarttls"
92 // Use TLS with STARTTLS if remote claims to support it.
93 TLSOpportunistic TLSMode = "opportunistic"
95 // TLS must not be attempted, e.g. due to earlier TLS handshake error.
96 TLSSkip TLSMode = "skip"
99// Client is an SMTP client that can deliver messages to a mail server.
101// Use New to make a new client.
103 // OrigConn is the original (TCP) connection. We'll read from/write to conn, which
104 // can be wrapped in a tls.Client. We close origConn instead of conn because
105 // closing the TLS connection would send a TLS close notification, which may block
106 // for 5s if the server isn't reading it (because it is also sending it).
110 ignoreTLSVerifyErrors bool
111 rootCAs *x509.CertPool
112 remoteHostname dns.Domain // TLS with SNI and name verification.
113 daneRecords []adns.TLSA // For authenticating (START)TLS connection.
114 daneMoreHostnames []dns.Domain // Additional allowed names in TLS certificate for DANE-TA.
115 daneVerifiedRecord *adns.TLSA // If non-nil, then will be set to verified DANE record if any.
116 clientCert *tls.Certificate // If non-nil, tls client authentication is done.
118 // TLS connection success/failure are added. These are always non-nil, regardless
119 // of what was passed in opts. It lets us unconditionally dereference them.
120 recipientDomainResult *tlsrpt.Result // Either "sts" or "no-policy-found".
121 hostResult *tlsrpt.Result // Either "dane" or "no-policy-found".
125 tr *moxio.TraceReader // Kept for changing trace levels between cmd/auth/data.
126 tw *moxio.TraceWriter
128 lastlog time.Time // For adding delta timestamps between log lines.
129 cmds []string // Last or active command, for generating errors and metrics.
130 cmdStart time.Time // Start of command.
131 tls bool // Whether connection is TLS protected.
132 firstReadAfterHandshake bool // To detect TLS alert error from remote just after handshake.
134 botched bool // If set, protocol is out of sync and no further commands can be sent.
135 needRset bool // If set, a new delivery requires an RSET command.
137 remoteHelo string // From 220 greeting line.
138 extEcodes bool // Remote server supports sending extended error codes.
139 extStartTLS bool // Remote server supports STARTTLS.
141 extSize bool // Remote server supports SIZE parameter. Must only be used if > 0.
142 maxSize int64 // Max size of email message.
143 extPipelining bool // Remote server supports command pipelining.
144 extSMTPUTF8 bool // Remote server supports SMTPUTF8 extension.
145 extAuthMechanisms []string // Supported authentication mechanisms.
146 extRequireTLS bool // Remote supports REQUIRETLS extension.
147 ExtLimits map[string]string // For LIMITS extension, only if present and valid, with uppercase keys.
148 ExtLimitMailMax int // Max "MAIL" commands in a connection, if > 0.
149 ExtLimitRcptMax int // Max "RCPT" commands in a transaction, if > 0.
150 ExtLimitRcptDomainMax int // Max unique domains in a connection, if > 0.
153// Error represents a failure to deliver a message.
155// Code, Secode, Command and Line are only set for SMTP-level errors, and are zero
158 // Whether failure is permanent, typically because of 5xx response.
160 // SMTP response status, e.g. 2xx for success, 4xx for transient error and 5xx for
161 // permanent failure.
163 // Short enhanced status, minus first digit and dot. Can be empty, e.g. for io
164 // errors or if remote does not send enhanced status codes. If remote responds with
165 // "550 5.7.1 ...", the Secode will be "7.1".
167 // SMTP command causing failure.
169 // For errors due to SMTP responses, the full SMTP line excluding CRLF that caused
170 // the error. First line of a multi-line response.
172 // Optional additional lines in case of multi-line SMTP response. Most SMTP
173 // responses are single-line, leaving this field empty.
175 // Underlying error, e.g. one of the Err variables in this package, or io errors.
181// Unwrap returns the underlying Err.
182func (e Error) Unwrap() error {
186// Error returns a readable error string.
187func (e Error) Error() string {
190 s = e.Err.Error() + ", "
203// Opts influence behaviour of Client.
205 // If auth is non-nil, authentication will be done with the returned sasl client.
206 // The function should select the preferred mechanism. Mechanisms are in upper
209 // The TLS connection state can be used for the SCRAM PLUS mechanisms, binding the
210 // authentication exchange to a TLS connection. It is only present for TLS
213 // If no mechanism is supported, a nil client and nil error can be returned, and
214 // the connection will fail.
215 Auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)
217 DANERecords []adns.TLSA // If not nil, DANE records to verify.
218 DANEMoreHostnames []dns.Domain // For use with DANE, where additional certificate host names are allowed.
219 DANEVerifiedRecord *adns.TLSA // If non-empty, set to the DANE record that verified the TLS connection.
221 // If set, TLS verification errors (for DANE or PKIX) are ignored. Useful for
222 // delivering messages with message header "TLS-Required: No".
223 // Certificates are still verified, and results are still tracked for TLS
224 // reporting, but the connections will continue.
225 IgnoreTLSVerifyErrors bool
227 // If not nil, used instead of the system default roots for TLS PKIX verification.
228 RootCAs *x509.CertPool
230 // If set, the TLS client certificate authentication is done.
231 ClientCert *tls.Certificate
233 // TLS verification successes/failures is added to these TLS reporting results.
234 // Once the STARTTLS handshake is attempted, a successful/failed connection is
236 RecipientDomainResult *tlsrpt.Result // MTA-STS or no policy.
237 HostResult *tlsrpt.Result // DANE or no policy.
240// New initializes an SMTP session on the given connection, returning a client that
241// can be used to deliver messages.
243// New optionally starts TLS (for submission), reads the server greeting,
244// identifies itself with a HELO or EHLO command, initializes TLS with STARTTLS if
245// remote supports it and optionally authenticates. If successful, a client is
246// returned on which eventually Close must be called. Otherwise an error is
247// returned and the caller is responsible for closing the connection.
249// Connecting to the correct host for delivery can be done using the Gather
250// functions, and with Dial. The queue managing outgoing messages typically decides
251// which host to deliver to, taking multiple MX records with preferences, other DNS
252// records, MTA-STS, retries and special cases into account.
254// tlsMode indicates if and how TLS may/must (not) be used.
256// tlsVerifyPKIX indicates if TLS certificates must be validated against the
257// PKIX/WebPKI certificate authorities (if TLS is done).
259// DANE-verification is done when opts.DANERecords is not nil.
261// TLS verification errors will be ignored if opts.IgnoreTLSVerification is set.
263// If TLS is done, PKIX verification is always performed for tracking the results
264// for TLS reporting, but if tlsVerifyPKIX is false, the verification result does
265// not affect the connection.
267// At the time of writing, delivery of email on the internet is done with
268// opportunistic TLS without PKIX verification by default. Recipient domains can
269// opt-in to PKIX verification by publishing an MTA-STS policy, or opt-in to DANE
270// verification by publishing DNSSEC-protected TLSA records in DNS.
271func New(ctx context.Context, elog *slog.Logger, conn net.Conn, tlsMode TLSMode, tlsVerifyPKIX bool, ehloHostname, remoteHostname dns.Domain, opts Opts) (*Client, error) {
272 ensureResult := func(r *tlsrpt.Result) *tlsrpt.Result {
274 return &tlsrpt.Result{}
281 tlsVerifyPKIX: tlsVerifyPKIX,
282 ignoreTLSVerifyErrors: opts.IgnoreTLSVerifyErrors,
283 rootCAs: opts.RootCAs,
284 remoteHostname: remoteHostname,
285 daneRecords: opts.DANERecords,
286 daneMoreHostnames: opts.DANEMoreHostnames,
287 daneVerifiedRecord: opts.DANEVerifiedRecord,
288 clientCert: opts.ClientCert,
290 cmds: []string{"(none)"},
291 recipientDomainResult: ensureResult(opts.RecipientDomainResult),
292 hostResult: ensureResult(opts.HostResult),
294 c.log = mlog.New("smtpclient", elog).WithFunc(func() []slog.Attr {
297 slog.Duration("delta", now.Sub(c.lastlog)),
303 if tlsMode == TLSImmediate {
304 config := c.tlsConfig()
305 tlsconn := tls.Client(conn, config)
306 // The tlsrpt tracking isn't used by caller, but won't hurt.
307 if err := tlsconn.HandshakeContext(ctx); err != nil {
308 c.tlsResultAdd(0, 1, err)
311 c.firstReadAfterHandshake = true
312 c.tlsResultAdd(1, 0, nil)
314 tlsversion, ciphersuite := moxio.TLSInfo(tlsconn)
315 c.log.Debug("tls client handshake done",
316 slog.String("tls", tlsversion),
317 slog.String("ciphersuite", ciphersuite),
318 slog.Any("servername", remoteHostname))
324 // We don't wrap reads in a timeoutReader for fear of an optional TLS wrapper doing
325 // reads without the client asking for it. Such reads could result in a timeout
327 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
328 c.r = bufio.NewReader(c.tr)
329 // We use a single write timeout of 30 seconds.
331 c.tw = moxio.NewTraceWriter(c.log, "LC: ", timeoutWriter{c.conn, 30 * time.Second, c.log})
332 c.w = bufio.NewWriter(c.tw)
334 if err := c.hello(ctx, tlsMode, ehloHostname, opts.Auth); err != nil {
340// reportedError wraps an error while indicating it was already tracked for TLS
342type reportedError struct{ err error }
344func (e reportedError) Error() string {
348func (e reportedError) Unwrap() error {
352func (c *Client) tlsConfig() *tls.Config {
353 // We always manage verification ourselves: We need to report in detail about
354 // failures. And we may have to verify both PKIX and DANE, record errors for
355 // each, and possibly ignore the errors.
357 verifyConnection := func(cs tls.ConnectionState) error {
358 // Collect verification errors. If there are none at the end, TLS validation
359 // succeeded. We may find validation problems below, record them for a TLS report
360 // but continue due to policies. We track the TLS reporting result in this
361 // function, wrapping errors in a reportedError.
362 var daneErr, pkixErr error
364 // DANE verification.
365 // daneRecords can be non-nil and empty, that's intended.
366 if c.daneRecords != nil {
367 verified, record, err := dane.Verify(c.log.Logger, c.daneRecords, cs, c.remoteHostname, c.daneMoreHostnames, c.rootCAs)
368 c.log.Debugx("dane verification", err, slog.Bool("verified", verified), slog.Any("record", record))
370 if c.daneVerifiedRecord != nil {
371 *c.daneVerifiedRecord = record
374 // Track error for reports.
375 // todo spec: may want to propose adding a result for no-dane-match. dane allows multiple records, some mismatching/failing isn't fatal and reporting on each record is probably not productive.
../rfc/8460:541
376 fd := c.tlsrptFailureDetails(tlsrpt.ResultValidationFailure, "dane-no-match")
378 // todo future: potentially add more details. e.g. dane-ta verification errors. tlsrpt does not have "result types" to indicate those kinds of errors. we would probably have to pass c.daneResult to dane.Verify.
380 // We may have encountered errors while evaluation some of the TLSA records.
381 fd.FailureReasonCode += "+errors"
383 c.hostResult.Add(0, 0, fd)
385 if c.ignoreTLSVerifyErrors {
386 // We ignore the failure and continue the connection.
387 c.log.Infox("verifying dane failed, continuing with connection", err)
388 MetricTLSRequiredNoIgnored.IncLabels("daneverification")
390 // This connection will fail.
391 daneErr = dane.ErrNoMatch
396 // PKIX verification.
397 opts := x509.VerifyOptions{
398 DNSName: cs.ServerName,
399 Intermediates: x509.NewCertPool(),
402 for _, cert := range cs.PeerCertificates[1:] {
403 opts.Intermediates.AddCert(cert)
405 if _, err := cs.PeerCertificates[0].Verify(opts); err != nil {
406 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
407 fd := c.tlsrptFailureDetails(resultType, reasonCode)
408 c.recipientDomainResult.Add(0, 0, fd)
410 if c.tlsVerifyPKIX && !c.ignoreTLSVerifyErrors {
415 if daneErr != nil && pkixErr != nil {
416 return reportedError{errors.Join(daneErr, pkixErr)}
417 } else if daneErr != nil {
418 return reportedError{daneErr}
419 } else if pkixErr != nil {
420 return reportedError{pkixErr}
425 var certs []tls.Certificate
426 if c.clientCert != nil {
427 certs = []tls.Certificate{*c.clientCert}
431 ServerName: c.remoteHostname.ASCII, // For SNI.
432 // todo: possibly accept older TLS versions for TLSOpportunistic? or would our private key be at risk?
434 InsecureSkipVerify: true, // VerifyConnection below is called and will do all verification.
435 VerifyConnection: verifyConnection,
440// xbotchf generates a temporary error and marks the client as botched. e.g. for
441// i/o errors or invalid protocol messages.
442func (c *Client) xbotchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) {
443 panic(c.botchf(code, secode, firstLine, moreLines, format, args...))
446// botchf generates a temporary error and marks the client as botched. e.g. for
447// i/o errors or invalid protocol messages.
448func (c *Client) botchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) error {
450 return c.errorf(false, code, secode, firstLine, moreLines, format, args...)
453func (c *Client) errorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) error {
458 return Error{permanent, code, secode, cmd, firstLine, moreLines, fmt.Errorf(format, args...)}
461func (c *Client) xerrorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) {
462 panic(c.errorf(permanent, code, secode, firstLine, moreLines, format, args...))
465// timeoutWriter passes each Write on to conn after setting a write deadline on conn based on
467type timeoutWriter struct {
469 timeout time.Duration
473func (w timeoutWriter) Write(buf []byte) (int, error) {
474 if err := w.conn.SetWriteDeadline(time.Now().Add(w.timeout)); err != nil {
475 w.log.Errorx("setting write deadline", err)
478 return w.conn.Write(buf)
481var bufs = moxio.NewBufpool(8, 2*1024)
483func (c *Client) readline() (string, error) {
484 // todo: could have per-operation timeouts. and rfc suggests higher minimum timeouts.
../rfc/5321:3610
485 if err := c.conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
486 c.log.Errorx("setting read deadline", err)
489 line, err := bufs.Readline(c.log, c.r)
491 // See if this is a TLS alert from remote, and one other than 0 (which notifies
492 // that the connection is being closed. If so, we register a TLS connection
493 // failure. This handles TLS alerts that happen just after a successful handshake.
494 var netErr *net.OpError
495 if c.firstReadAfterHandshake && errors.As(err, &netErr) && netErr.Op == "remote error" && netErr.Err != nil && reflect.ValueOf(netErr.Err).Kind() == reflect.Uint8 && reflect.ValueOf(netErr.Err).Uint() != 0 {
496 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
497 // We count -1 success to compensate for the assumed success right after the handshake.
498 c.tlsResultAddFailureDetails(-1, 1, c.tlsrptFailureDetails(resultType, reasonCode))
501 return line, c.botchf(0, "", "", nil, "%s: %w", strings.Join(c.cmds, ","), err)
503 c.firstReadAfterHandshake = false
507func (c *Client) xtrace(level slog.Level) func() {
513 c.tr.SetTrace(mlog.LevelTrace)
514 c.tw.SetTrace(mlog.LevelTrace)
518func (c *Client) xwritelinef(format string, args ...any) {
519 c.xbwritelinef(format, args...)
523func (c *Client) xwriteline(line string) {
528func (c *Client) xbwritelinef(format string, args ...any) {
529 c.xbwriteline(fmt.Sprintf(format, args...))
532func (c *Client) xbwriteline(line string) {
533 _, err := fmt.Fprintf(c.w, "%s\r\n", line)
535 c.xbotchf(0, "", "", nil, "write: %w", err)
539func (c *Client) xflush() {
542 c.xbotchf(0, "", "", nil, "writes: %w", err)
546// read response, possibly multiline, with supporting extended codes based on configuration in client.
547func (c *Client) xread() (code int, secode, firstLine string, moreLines []string) {
549 code, secode, firstLine, moreLines, err = c.read()
556func (c *Client) read() (code int, secode, firstLine string, moreLines []string, rerr error) {
557 code, secode, _, firstLine, moreLines, _, rerr = c.readecode(c.extEcodes)
561// read response, possibly multiline.
562// if ecodes, extended codes are parsed.
563func (c *Client) readecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string, rerr error) {
566 co, sec, text, line, last, err := c.read1(ecodes)
570 } else if line != "" {
571 moreLines = append(moreLines, line)
573 moreTexts = append(moreTexts, text)
580 if code != 0 && co != code {
582 err := c.botchf(0, "", firstLine, moreLines, "%w: multiline response with different codes, previous %d, last %d", ErrProtocol, code, co)
583 return 0, "", "", "", nil, nil, err
587 if code != smtp.C334ContinueAuth {
591 // We only keep the last, so we're not creating new slices all the time.
596 MetricCommands.ObserveLabels(float64(time.Since(c.cmdStart))/float64(time.Second), cmd, fmt.Sprintf("%d", co), sec)
597 c.log.Debug("smtpclient command result",
598 slog.String("cmd", cmd),
599 slog.Int("code", co),
600 slog.String("secode", sec),
601 slog.Duration("duration", time.Since(c.cmdStart)))
603 return co, sec, text, firstLine, moreLines, moreTexts, nil
608func (c *Client) xreadecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string) {
610 code, secode, lastText, firstLine, moreLines, moreTexts, err = c.readecode(ecodes)
617// read single response line.
618// if ecodes, extended codes are parsed.
619func (c *Client) read1(ecodes bool) (code int, secode, text, line string, last bool, rerr error) {
620 line, rerr = c.readline()
625 for ; i < len(line) && line[i] >= '0' && line[i] <= '9'; i++ {
628 rerr = c.botchf(0, "", line, nil, "%w: expected response code: %s", ErrProtocol, line)
631 v, err := strconv.ParseInt(line[:i], 10, 32)
633 rerr = c.botchf(0, "", line, nil, "%w: bad response code (%s): %s", ErrProtocol, err, line)
639 if strings.HasPrefix(s, "-") || strings.HasPrefix(s, " ") {
646 rerr = c.botchf(0, "", line, nil, "%w: expected space or dash after response code: %s", ErrProtocol, line)
651 secode, s = parseEcode(major, s)
654 return code, secode, s, line, last, nil
657func parseEcode(major int, s string) (secode string, remain string) {
660 take := func(need bool, a, b byte) bool {
661 if !bad && o < len(s) && s[o] >= a && s[o] <= b {
668 digit := func(need bool) bool {
669 return take(need, '0', '9')
672 return take(true, '.', '.')
686 take(false, ' ', ' ')
687 if bad || int(s[0])-int('0') != major {
693func (c *Client) recover(rerr *error) {
698 cerr, ok := x.(Error)
706func (c *Client) hello(ctx context.Context, tlsMode TLSMode, ehloHostname dns.Domain, auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
707 defer c.recover(&rerr)
709 // perform EHLO handshake, falling back to HELO if server does not appear to
711 hello := func(heloOK bool) {
712 // Write EHLO and parse the supported extensions.
715 c.cmdStart = time.Now()
717 c.xwritelinef("EHLO %s", ehloHostname.ASCII)
718 code, _, _, firstLine, moreLines, moreTexts := c.xreadecode(false)
722 case smtp.C500BadSyntax, smtp.C501BadParamSyntax, smtp.C502CmdNotImpl, smtp.C503BadCmdSeq, smtp.C504ParamNotImpl:
724 c.xerrorf(true, code, "", firstLine, moreLines, "%w: remote claims ehlo is not supported", ErrProtocol)
728 c.cmdStart = time.Now()
729 c.xwritelinef("HELO %s", ehloHostname.ASCII)
730 code, _, _, firstLine, _, _ = c.xreadecode(false)
731 if code != smtp.C250Completed {
732 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250 to HELO, got %d", ErrStatus, code)
735 case smtp.C250Completed:
737 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250, got %d", ErrStatus, code)
739 for _, s := range moreTexts {
741 s = strings.ToUpper(strings.TrimSpace(s))
745 case "ENHANCEDSTATUSCODES":
750 c.extPipelining = true
752 c.extRequireTLS = true
755 if s == "SMTPUTF8" || strings.HasPrefix(s, "SMTPUTF8 ") {
757 } else if strings.HasPrefix(s, "SIZE ") {
760 if v, err := strconv.ParseInt(s[len("SIZE "):], 10, 64); err == nil {
763 } else if strings.HasPrefix(s, "AUTH ") {
764 c.extAuthMechanisms = strings.Split(s[len("AUTH "):], " ")
765 } else if strings.HasPrefix(s, "LIMITS ") {
766 c.ExtLimits, c.ExtLimitMailMax, c.ExtLimitRcptMax, c.ExtLimitRcptDomainMax = parseLimits([]byte(s[len("LIMITS"):]))
773 c.cmds = []string{"(greeting)"}
774 c.cmdStart = time.Now()
775 code, _, _, firstLine, moreLines, _ := c.xreadecode(false)
776 if code != smtp.C220ServiceReady {
777 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 220, got %d", ErrStatus, code)
780 _, c.remoteHelo, _ = strings.Cut(firstLine, " ")
782 // Write EHLO, falling back to HELO if server doesn't appear to support it.
785 // Attempt TLS if remote understands STARTTLS and we aren't doing immediate TLS or if caller requires it.
786 if c.extStartTLS && tlsMode == TLSOpportunistic || tlsMode == TLSRequiredStartTLS {
787 c.log.Debug("starting tls client", slog.Any("tlsmode", tlsMode), slog.Any("servername", c.remoteHostname))
788 c.cmds[0] = "starttls"
789 c.cmdStart = time.Now()
790 c.xwritelinef("STARTTLS")
791 code, secode, firstLine, _ := c.xread()
793 if code != smtp.C220ServiceReady {
794 c.tlsResultAddFailureDetails(0, 1, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, fmt.Sprintf("smtp-starttls-reply-code-%d", code)))
795 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: STARTTLS: got %d, expected 220", ErrTLS, code)
798 // We don't want to do TLS on top of c.r because it also prints protocol traces: We
799 // don't want to log the TLS stream. So we'll do TLS on the underlying connection,
800 // but make sure any bytes already read and in the buffer are used for the TLS
803 if n := c.r.Buffered(); n > 0 {
804 conn = &moxio.PrefixConn{
805 PrefixReader: io.LimitReader(c.r, int64(n)),
810 tlsConfig := c.tlsConfig()
811 nconn := tls.Client(conn, tlsConfig)
814 nctx, cancel := context.WithTimeout(ctx, time.Minute)
816 err := nconn.HandshakeContext(nctx)
818 // For each STARTTLS failure, we track a failed TLS session. For deliveries with
819 // multiple MX targets, we may add multiple failures, and delivery may succeed with
821 c.tlsResultAdd(0, 1, err)
822 c.xerrorf(false, 0, "", "", nil, "%w: STARTTLS TLS handshake: %s", ErrTLS, err)
824 c.firstReadAfterHandshake = true
826 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
827 c.tw = moxio.NewTraceWriter(c.log, "LC: ", c.conn) // No need to wrap in timeoutWriter, it would just set the timeout on the underlying connection, which is still active.
828 c.r = bufio.NewReader(c.tr)
829 c.w = bufio.NewWriter(c.tw)
831 tlsversion, ciphersuite := moxio.TLSInfo(nconn)
832 c.log.Debug("starttls client handshake done",
833 slog.Any("tlsmode", tlsMode),
834 slog.Bool("verifypkix", c.tlsVerifyPKIX),
835 slog.Bool("verifydane", c.daneRecords != nil),
836 slog.Bool("ignoretlsverifyerrors", c.ignoreTLSVerifyErrors),
837 slog.String("tls", tlsversion),
838 slog.String("ciphersuite", ciphersuite),
839 slog.Any("servername", c.remoteHostname),
840 slog.Any("danerecord", c.daneVerifiedRecord))
843 c.tlsResultAdd(1, 0, nil)
846 } else if tlsMode == TLSOpportunistic {
848 c.tlsResultAddFailureDetails(0, 0, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, ""))
857// parse text after "LIMITS", including leading space.
858func parseLimits(b []byte) (map[string]string, int, int, int) {
861 // Read next " name=value".
862 pair := func() ([]byte, []byte) {
863 if o >= len(b) || b[o] != ' ' {
871 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' {
878 if ns == es || o >= len(b) || b[o] != '=' {
885 if c > 0x20 && c < 0x7f && c != ';' {
894 return b[ns:es], b[vs:o]
896 limits := map[string]string{}
897 var mailMax, rcptMax, rcptDomainMax int
899 name, value := pair()
904 k := strings.ToUpper(string(name))
905 if _, ok := limits[k]; ok {
906 // Not specified, but we treat duplicates as error.
909 limits[k] = string(value)
910 // For individual value syntax errors, we skip that value, leaving the default 0.
912 switch string(name) {
914 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
918 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
921 case "RCPTDOMAINMAX":
922 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
927 return limits, mailMax, rcptMax, rcptDomainMax
930func addrIP(addr net.Addr) string {
931 if t, ok := addr.(*net.TCPAddr); ok {
934 host, _, _ := net.SplitHostPort(addr.String())
935 ip := net.ParseIP(host)
937 return "" // For pipe during tests.
942// tlsrptFailureDetails returns FailureDetails with connection details (such as
943// IP addresses) for inclusion in a TLS report.
944func (c *Client) tlsrptFailureDetails(resultType tlsrpt.ResultType, reasonCode string) tlsrpt.FailureDetails {
945 return tlsrpt.FailureDetails{
946 ResultType: resultType,
947 SendingMTAIP: addrIP(c.origConn.LocalAddr()),
948 ReceivingMXHostname: c.remoteHostname.ASCII,
949 ReceivingMXHelo: c.remoteHelo,
950 ReceivingIP: addrIP(c.origConn.RemoteAddr()),
951 FailedSessionCount: 1,
952 FailureReasonCode: reasonCode,
956// tlsResultAdd adds TLS success/failure to all results.
957func (c *Client) tlsResultAdd(success, failure int64, err error) {
958 // Only track failure if not already done so in tls.Config.VerifyConnection.
959 var fds []tlsrpt.FailureDetails
960 var repErr reportedError
961 if err != nil && !errors.As(err, &repErr) {
962 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
963 fd := c.tlsrptFailureDetails(resultType, reasonCode)
964 fds = []tlsrpt.FailureDetails{fd}
966 c.tlsResultAddFailureDetails(success, failure, fds...)
969func (c *Client) tlsResultAddFailureDetails(success, failure int64, fds ...tlsrpt.FailureDetails) {
970 c.recipientDomainResult.Add(success, failure, fds...)
971 c.hostResult.Add(success, failure, fds...)
975func (c *Client) auth(auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
976 defer c.recover(&rerr)
979 c.cmdStart = time.Now()
981 mechanisms := make([]string, len(c.extAuthMechanisms))
982 for i, m := range c.extAuthMechanisms {
983 mechanisms[i] = strings.ToUpper(m)
985 a, err := auth(mechanisms, c.TLSConnectionState())
987 c.xerrorf(true, 0, "", "", nil, "get authentication mechanism: %s, server supports %s", err, strings.Join(c.extAuthMechanisms, ", "))
989 c.xerrorf(true, 0, "", "", nil, "no matching authentication mechanisms, server supports %s", strings.Join(c.extAuthMechanisms, ", "))
991 name, cleartextCreds := a.Info()
993 abort := func() (int, string, string, []string) {
998 code, secode, firstLine, moreLines := c.xread()
999 if code != smtp.C501BadParamSyntax {
1002 return code, secode, firstLine, moreLines
1005 toserver, last, err := a.Next(nil)
1007 c.xerrorf(false, 0, "", "", nil, "initial step in auth mechanism %s: %w", name, err)
1010 defer c.xtrace(mlog.LevelTraceauth)()
1012 if toserver == nil {
1013 c.xwriteline("AUTH " + name)
1014 } else if len(toserver) == 0 {
1017 c.xwriteline("AUTH " + name + " " + base64.StdEncoding.EncodeToString(toserver))
1020 if cleartextCreds && last {
1021 c.xtrace(mlog.LevelTrace) // Restore.
1024 code, secode, lastText, firstLine, moreLines, _ := c.xreadecode(last)
1025 if code == smtp.C235AuthSuccess {
1027 c.xerrorf(false, code, secode, firstLine, moreLines, "server completed authentication earlier than client expected")
1030 } else if code == smtp.C334ContinueAuth {
1032 c.xerrorf(false, code, secode, firstLine, moreLines, "server requested unexpected continuation of authentication")
1034 if len(moreLines) > 0 {
1036 c.xerrorf(false, code, secode, firstLine, moreLines, "server responded with multiline contination")
1038 fromserver, err := base64.StdEncoding.DecodeString(lastText)
1041 c.xerrorf(false, code, secode, firstLine, moreLines, "malformed base64 data in authentication continuation response")
1043 toserver, last, err = a.Next(fromserver)
1045 // For failing SCRAM, the client stops due to message about invalid proof. The
1046 // server still sends an authentication result (it probably should send 501
1048 xcode, xsecode, xfirstLine, xmoreLines := abort()
1049 c.xerrorf(false, xcode, xsecode, xfirstLine, xmoreLines, "client aborted authentication: %w", err)
1051 c.xwriteline(base64.StdEncoding.EncodeToString(toserver))
1053 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "unexpected response during authentication, expected 334 continue or 235 auth success")
1058// Supports8BITMIME returns whether the SMTP server supports the 8BITMIME
1059// extension, needed for sending data with non-ASCII bytes.
1060func (c *Client) Supports8BITMIME() bool {
1061 return c.ext8bitmime
1064// SupportsSMTPUTF8 returns whether the SMTP server supports the SMTPUTF8
1065// extension, needed for sending messages with UTF-8 in headers or in an (SMTP)
1067func (c *Client) SupportsSMTPUTF8() bool {
1068 return c.extSMTPUTF8
1071// SupportsStartTLS returns whether the SMTP server supports the STARTTLS
1073func (c *Client) SupportsStartTLS() bool {
1074 return c.extStartTLS
1077// SupportsRequireTLS returns whether the SMTP server supports the REQUIRETLS
1078// extension. The REQUIRETLS extension is only announced after enabling
1080func (c *Client) SupportsRequireTLS() bool {
1081 return c.extRequireTLS
1084// TLSConnectionState returns TLS details if TLS is enabled, and nil otherwise.
1085func (c *Client) TLSConnectionState() *tls.ConnectionState {
1086 if tlsConn, ok := c.conn.(*tls.Conn); ok {
1087 cs := tlsConn.ConnectionState()
1093// Deliver attempts to deliver a message to a mail server.
1095// mailFrom must be an email address, or empty in case of a DSN. rcptTo must be
1098// If the message contains bytes with the high bit set, req8bitmime must be true. If
1099// set, the remote server must support the 8BITMIME extension or delivery will
1102// If the message is internationalized, e.g. when headers contain non-ASCII
1103// character, or when UTF-8 is used in a localpart, reqSMTPUTF8 must be true. If set,
1104// the remote server must support the SMTPUTF8 extension or delivery will fail.
1106// If requireTLS is true, the remote server must support the REQUIRETLS
1107// extension, or delivery will fail.
1109// Deliver uses the following SMTP extensions if the remote server supports them:
1110// 8BITMIME, SMTPUTF8, SIZE, PIPELINING, ENHANCEDSTATUSCODES, STARTTLS.
1112// Returned errors can be of type Error, one of the Err-variables in this package
1113// or other underlying errors, e.g. for i/o. Use errors.Is to check.
1114func (c *Client) Deliver(ctx context.Context, mailFrom string, rcptTo string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rerr error) {
1115 _, err := c.DeliverMultiple(ctx, mailFrom, []string{rcptTo}, msgSize, msg, req8bitmime, reqSMTPUTF8, requireTLS)
1119var errNoRecipientsPipelined = errors.New("no recipients accepted in pipelined transaction")
1120var errNoRecipients = errors.New("no recipients accepted in transaction")
1122// DeliverMultiple is like Deliver, but attempts to deliver a message to multiple
1123// recipients. Errors about the entire transaction, such as i/o errors or error
1124// responses to the MAIL FROM or DATA commands, are returned by a non-nil rerr. If
1125// rcptTo has a single recipient, an error to the RCPT TO command is returned in
1126// rerr instead of rcptResps. Otherwise, the SMTP response for each recipient is
1127// returned in rcptResps.
1129// The caller should take extLimit* into account when sending. And recognize
1130// recipient response code "452" to mean that a recipient limit was reached,
1131// another transaction can be attempted immediately after instead of marking the
1132// delivery attempt as failed. Also code "552" must be treated like temporary error
1133// code "452" for historic reasons.
1134func (c *Client) DeliverMultiple(ctx context.Context, mailFrom string, rcptTo []string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rcptResps []Response, rerr error) {
1135 defer c.recover(&rerr)
1137 if len(rcptTo) == 0 {
1138 return nil, fmt.Errorf("need at least one recipient")
1141 if c.origConn == nil {
1142 return nil, ErrClosed
1143 } else if c.botched {
1144 return nil, ErrBotched
1145 } else if c.needRset {
1146 if err := c.Reset(); err != nil {
1151 if !c.ext8bitmime && req8bitmime {
1152 // Temporary error, e.g. OpenBSD spamd does not announce 8bitmime support, but once
1153 // you get through, the mail server behind it probably does. Just needs a few
1155 c.xerrorf(false, 0, "", "", nil, "%w", Err8bitmimeUnsupported)
1157 if !c.extSMTPUTF8 && reqSMTPUTF8 {
1159 c.xerrorf(false, 0, "", "", nil, "%w", ErrSMTPUTF8Unsupported)
1161 if !c.extRequireTLS && requireTLS {
1162 c.xerrorf(false, 0, "", "", nil, "%w", ErrRequireTLSUnsupported)
1166 if c.extSize && c.maxSize > 0 && msgSize > c.maxSize {
1167 c.xerrorf(true, 0, "", "", nil, "%w: message is %d bytes, remote has a %d bytes maximum size", ErrSize, msgSize, c.maxSize)
1170 var mailSize, bodyType string
1172 mailSize = fmt.Sprintf(" SIZE=%d", msgSize)
1176 bodyType = " BODY=8BITMIME"
1178 bodyType = " BODY=7BIT"
1181 var smtputf8Arg string
1184 smtputf8Arg = " SMTPUTF8"
1186 var requiretlsArg string
1189 requiretlsArg = " REQUIRETLS"
1196 lineMailFrom := fmt.Sprintf("MAIL FROM:<%s>%s%s%s%s", mailFrom, mailSize, bodyType, smtputf8Arg, requiretlsArg)
1198 // We are going into a transaction. We'll clear this when done.
1201 if c.extPipelining {
1202 c.cmds = make([]string, 1+len(rcptTo)+1)
1203 c.cmds[0] = "mailfrom"
1204 for i := range rcptTo {
1205 c.cmds[1+i] = "rcptto"
1207 c.cmds[len(c.cmds)-1] = "data"
1208 c.cmdStart = time.Now()
1210 // Write and read in separte goroutines. Otherwise, writing a large recipient list
1211 // could block when a server doesn't read more commands before we read their
1213 errc := make(chan error, 1)
1214 // Make sure we don't return before we're done writing to the connection.
1222 b.WriteString(lineMailFrom)
1223 b.WriteString("\r\n")
1224 for _, rcpt := range rcptTo {
1225 b.WriteString("RCPT TO:<")
1227 b.WriteString(">\r\n")
1229 b.WriteString("DATA\r\n")
1230 _, err := c.w.Write(b.Bytes())
1237 // Read response to MAIL FROM.
1238 mfcode, mfsecode, mffirstLine, mfmoreLines := c.xread()
1240 // We read the response to RCPT TOs and DATA without panic on read error. Servers
1241 // may be aborting the connection after a failed MAIL FROM, e.g. outlook when it
1242 // has blocklisted your IP. We don't want the read for the response to RCPT TO to
1243 // cause a read error as it would result in an unhelpful error message and a
1244 // temporary instead of permanent error code.
1246 // Read responses to RCPT TO.
1247 rcptResps = make([]Response, len(rcptTo))
1249 for i := 0; i < len(rcptTo); i++ {
1250 code, secode, firstLine, moreLines, err := c.read()
1252 permanent := code/100 == 5 && code != smtp.C552MailboxFull
1253 rcptResps[i] = Response{permanent, code, secode, "rcptto", firstLine, moreLines, err}
1254 if code == smtp.C250Completed {
1259 // Read response to DATA.
1260 datacode, datasecode, datafirstLine, datamoreLines, dataerr := c.read()
1265 // If MAIL FROM failed, it's an error for the entire transaction. We may have been
1267 if mfcode != smtp.C250Completed {
1268 if writeerr != nil || dataerr != nil {
1271 c.xerrorf(mfcode/100 == 5, mfcode, mfsecode, mffirstLine, mfmoreLines, "%w: got %d, expected 2xx", ErrStatus, mfcode)
1274 // If there was an i/o error writing the commands, there is no point continuing.
1275 if writeerr != nil {
1276 c.xbotchf(0, "", "", nil, "writing pipelined mail/rcpt/data: %w", writeerr)
1279 // If remote closed the connection before writing a DATA response, and the RCPT
1280 // TO's failed (e.g. after deciding we're on a blocklist), use the last response
1281 // for a rcptto as result.
1282 if dataerr != nil && errors.Is(dataerr, io.ErrUnexpectedEOF) && nok == 0 {
1284 r := rcptResps[len(rcptResps)-1]
1285 c.xerrorf(r.Permanent, r.Code, r.Secode, r.Line, r.MoreLines, "%w: server closed connection just before responding to data command", ErrStatus)
1288 // If the data command had an i/o or protocol error, it's also a failure for the
1289 // entire transaction.
1294 // If we didn't have any successful recipient, there is no point in continuing.
1296 // Servers may return success for a DATA without valid recipients. Write a dot to
1297 // end DATA and restore the connection to a known state.
1299 if datacode == smtp.C354Continue {
1300 _, doterr := fmt.Fprintf(c.w, ".\r\n")
1302 doterr = c.w.Flush()
1305 _, _, _, _, doterr = c.read()
1312 if len(rcptTo) == 1 {
1313 panic(Error(rcptResps[0]))
1315 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipientsPipelined)
1318 if datacode != smtp.C354Continue {
1319 c.xerrorf(datacode/100 == 5, datacode, datasecode, datafirstLine, datamoreLines, "%w: got %d, expected 354", ErrStatus, datacode)
1323 c.cmds[0] = "mailfrom"
1324 c.cmdStart = time.Now()
1325 c.xwriteline(lineMailFrom)
1326 code, secode, firstLine, moreLines := c.xread()
1327 if code != smtp.C250Completed {
1328 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1331 rcptResps = make([]Response, len(rcptTo))
1333 for i, rcpt := range rcptTo {
1334 c.cmds[0] = "rcptto"
1335 c.cmdStart = time.Now()
1336 c.xwriteline(fmt.Sprintf("RCPT TO:<%s>", rcpt))
1337 code, secode, firstLine, moreLines = c.xread()
1338 if i > 0 && (code == smtp.C452StorageFull || code == smtp.C552MailboxFull) {
1339 // Remote doesn't accept more recipients for this transaction. Don't send more, give
1340 // remaining recipients the same error result.
1341 for j := i; j < len(rcptTo); j++ {
1342 rcptResps[j] = Response{false, code, secode, "rcptto", firstLine, moreLines, fmt.Errorf("no more recipients accepted in transaction")}
1347 if code == smtp.C250Completed {
1350 err = fmt.Errorf("%w: got %d, expected 2xx", ErrStatus, code)
1352 rcptResps[i] = Response{code/100 == 5, code, secode, "rcptto", firstLine, moreLines, err}
1356 if len(rcptTo) == 1 {
1357 panic(Error(rcptResps[0]))
1359 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipients)
1363 c.cmdStart = time.Now()
1364 c.xwriteline("DATA")
1365 code, secode, firstLine, moreLines = c.xread()
1366 if code != smtp.C354Continue {
1367 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 354", ErrStatus, code)
1371 // For a DATA write, the suggested timeout is 3 minutes, we use 30 seconds for all
1373 defer c.xtrace(mlog.LevelTracedata)()
1374 err := smtp.DataWrite(c.w, msg)
1376 c.xbotchf(0, "", "", nil, "writing message as smtp data: %w", err)
1379 c.xtrace(mlog.LevelTrace) // Restore.
1380 code, secode, firstLine, moreLines := c.xread()
1381 if code != smtp.C250Completed {
1382 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1389// Reset sends an SMTP RSET command to reset the message transaction state. Deliver
1390// automatically sends it if needed.
1391func (c *Client) Reset() (rerr error) {
1392 if c.origConn == nil {
1394 } else if c.botched {
1398 defer c.recover(&rerr)
1402 c.cmdStart = time.Now()
1403 c.xwriteline("RSET")
1404 code, secode, firstLine, moreLines := c.xread()
1405 if code != smtp.C250Completed {
1406 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1412// Botched returns whether this connection is botched, e.g. a protocol error
1413// occurred and the connection is in unknown state, and cannot be used for message
1415func (c *Client) Botched() bool {
1416 return c.botched || c.origConn == nil
1419// Close cleans up the client, closing the underlying connection.
1421// If the connection is initialized and not botched, a QUIT command is sent and the
1422// response read with a short timeout before closing the underlying connection.
1424// Close returns any error encountered during QUIT and closing.
1425func (c *Client) Close() (rerr error) {
1426 if c.origConn == nil {
1430 defer c.recover(&rerr)
1435 c.cmdStart = time.Now()
1436 c.xwriteline("QUIT")
1437 if err := c.conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
1438 c.log.Infox("setting read deadline for reading quit response", err)
1439 } else if _, err := bufs.Readline(c.log, c.r); err != nil {
1440 rerr = fmt.Errorf("reading response to quit command: %v", err)
1441 c.log.Debugx("reading quit response", err)
1445 err := c.origConn.Close()
1446 if c.conn != c.origConn {
1447 // This is the TLS connection. Close will attempt to write a close notification.
1448 // But it will fail quickly because the underlying socket was closed.
1459// Conn returns the connection with initialized SMTP session. Once the caller uses
1460// this connection it is in control, and responsible for closing the connection,
1461// and other functions on the client must not be called anymore.
1462func (c *Client) Conn() (net.Conn, error) {
1463 if err := c.conn.SetDeadline(time.Time{}); err != nil {
1464 return nil, fmt.Errorf("clearing io deadlines: %w", err)