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.
117 // TLS connection success/failure are added. These are always non-nil, regardless
118 // of what was passed in opts. It lets us unconditionally dereference them.
119 recipientDomainResult *tlsrpt.Result // Either "sts" or "no-policy-found".
120 hostResult *tlsrpt.Result // Either "dane" or "no-policy-found".
124 tr *moxio.TraceReader // Kept for changing trace levels between cmd/auth/data.
125 tw *moxio.TraceWriter
127 lastlog time.Time // For adding delta timestamps between log lines.
128 cmds []string // Last or active command, for generating errors and metrics.
129 cmdStart time.Time // Start of command.
130 tls bool // Whether connection is TLS protected.
131 firstReadAfterHandshake bool // To detect TLS alert error from remote just after handshake.
133 botched bool // If set, protocol is out of sync and no further commands can be sent.
134 needRset bool // If set, a new delivery requires an RSET command.
136 remoteHelo string // From 220 greeting line.
137 extEcodes bool // Remote server supports sending extended error codes.
138 extStartTLS bool // Remote server supports STARTTLS.
140 extSize bool // Remote server supports SIZE parameter. Must only be used if > 0.
141 maxSize int64 // Max size of email message.
142 extPipelining bool // Remote server supports command pipelining.
143 extSMTPUTF8 bool // Remote server supports SMTPUTF8 extension.
144 extAuthMechanisms []string // Supported authentication mechanisms.
145 extRequireTLS bool // Remote supports REQUIRETLS extension.
146 ExtLimits map[string]string // For LIMITS extension, only if present and valid, with uppercase keys.
147 ExtLimitMailMax int // Max "MAIL" commands in a connection, if > 0.
148 ExtLimitRcptMax int // Max "RCPT" commands in a transaction, if > 0.
149 ExtLimitRcptDomainMax int // Max unique domains in a connection, if > 0.
152// Error represents a failure to deliver a message.
154// Code, Secode, Command and Line are only set for SMTP-level errors, and are zero
157 // Whether failure is permanent, typically because of 5xx response.
159 // SMTP response status, e.g. 2xx for success, 4xx for transient error and 5xx for
160 // permanent failure.
162 // Short enhanced status, minus first digit and dot. Can be empty, e.g. for io
163 // errors or if remote does not send enhanced status codes. If remote responds with
164 // "550 5.7.1 ...", the Secode will be "7.1".
166 // SMTP command causing failure.
168 // For errors due to SMTP responses, the full SMTP line excluding CRLF that caused
169 // the error. First line of a multi-line response.
171 // Optional additional lines in case of multi-line SMTP response. Most SMTP
172 // responses are single-line, leaving this field empty.
174 // Underlying error, e.g. one of the Err variables in this package, or io errors.
180// Unwrap returns the underlying Err.
181func (e Error) Unwrap() error {
185// Error returns a readable error string.
186func (e Error) Error() string {
189 s = e.Err.Error() + ", "
202// Opts influence behaviour of Client.
204 // If auth is non-nil, authentication will be done with the returned sasl client.
205 // The function should select the preferred mechanism. Mechanisms are in upper
208 // The TLS connection state can be used for the SCRAM PLUS mechanisms, binding the
209 // authentication exchange to a TLS connection. It is only present for TLS
212 // If no mechanism is supported, a nil client and nil error can be returned, and
213 // the connection will fail.
214 Auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)
216 DANERecords []adns.TLSA // If not nil, DANE records to verify.
217 DANEMoreHostnames []dns.Domain // For use with DANE, where additional certificate host names are allowed.
218 DANEVerifiedRecord *adns.TLSA // If non-empty, set to the DANE record that verified the TLS connection.
220 // If set, TLS verification errors (for DANE or PKIX) are ignored. Useful for
221 // delivering messages with message header "TLS-Required: No".
222 // Certificates are still verified, and results are still tracked for TLS
223 // reporting, but the connections will continue.
224 IgnoreTLSVerifyErrors bool
226 // If not nil, used instead of the system default roots for TLS PKIX verification.
227 RootCAs *x509.CertPool
229 // TLS verification successes/failures is added to these TLS reporting results.
230 // Once the STARTTLS handshake is attempted, a successful/failed connection is
232 RecipientDomainResult *tlsrpt.Result // MTA-STS or no policy.
233 HostResult *tlsrpt.Result // DANE or no policy.
236// New initializes an SMTP session on the given connection, returning a client that
237// can be used to deliver messages.
239// New optionally starts TLS (for submission), reads the server greeting,
240// identifies itself with a HELO or EHLO command, initializes TLS with STARTTLS if
241// remote supports it and optionally authenticates. If successful, a client is
242// returned on which eventually Close must be called. Otherwise an error is
243// returned and the caller is responsible for closing the connection.
245// Connecting to the correct host for delivery can be done using the Gather
246// functions, and with Dial. The queue managing outgoing messages typically decides
247// which host to deliver to, taking multiple MX records with preferences, other DNS
248// records, MTA-STS, retries and special cases into account.
250// tlsMode indicates if and how TLS may/must (not) be used.
252// tlsVerifyPKIX indicates if TLS certificates must be validated against the
253// PKIX/WebPKI certificate authorities (if TLS is done).
255// DANE-verification is done when opts.DANERecords is not nil.
257// TLS verification errors will be ignored if opts.IgnoreTLSVerification is set.
259// If TLS is done, PKIX verification is always performed for tracking the results
260// for TLS reporting, but if tlsVerifyPKIX is false, the verification result does
261// not affect the connection.
263// At the time of writing, delivery of email on the internet is done with
264// opportunistic TLS without PKIX verification by default. Recipient domains can
265// opt-in to PKIX verification by publishing an MTA-STS policy, or opt-in to DANE
266// verification by publishing DNSSEC-protected TLSA records in DNS.
267func New(ctx context.Context, elog *slog.Logger, conn net.Conn, tlsMode TLSMode, tlsVerifyPKIX bool, ehloHostname, remoteHostname dns.Domain, opts Opts) (*Client, error) {
268 ensureResult := func(r *tlsrpt.Result) *tlsrpt.Result {
270 return &tlsrpt.Result{}
277 tlsVerifyPKIX: tlsVerifyPKIX,
278 ignoreTLSVerifyErrors: opts.IgnoreTLSVerifyErrors,
279 rootCAs: opts.RootCAs,
280 remoteHostname: remoteHostname,
281 daneRecords: opts.DANERecords,
282 daneMoreHostnames: opts.DANEMoreHostnames,
283 daneVerifiedRecord: opts.DANEVerifiedRecord,
285 cmds: []string{"(none)"},
286 recipientDomainResult: ensureResult(opts.RecipientDomainResult),
287 hostResult: ensureResult(opts.HostResult),
289 c.log = mlog.New("smtpclient", elog).WithFunc(func() []slog.Attr {
292 slog.Duration("delta", now.Sub(c.lastlog)),
298 if tlsMode == TLSImmediate {
299 config := c.tlsConfig()
300 tlsconn := tls.Client(conn, config)
301 // The tlsrpt tracking isn't used by caller, but won't hurt.
302 if err := tlsconn.HandshakeContext(ctx); err != nil {
303 c.tlsResultAdd(0, 1, err)
306 c.firstReadAfterHandshake = true
307 c.tlsResultAdd(1, 0, nil)
309 tlsversion, ciphersuite := moxio.TLSInfo(tlsconn)
310 c.log.Debug("tls client handshake done",
311 slog.String("tls", tlsversion),
312 slog.String("ciphersuite", ciphersuite),
313 slog.Any("servername", remoteHostname))
319 // We don't wrap reads in a timeoutReader for fear of an optional TLS wrapper doing
320 // reads without the client asking for it. Such reads could result in a timeout
322 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
323 c.r = bufio.NewReader(c.tr)
324 // We use a single write timeout of 30 seconds.
326 c.tw = moxio.NewTraceWriter(c.log, "LC: ", timeoutWriter{c.conn, 30 * time.Second, c.log})
327 c.w = bufio.NewWriter(c.tw)
329 if err := c.hello(ctx, tlsMode, ehloHostname, opts.Auth); err != nil {
335// reportedError wraps an error while indicating it was already tracked for TLS
337type reportedError struct{ err error }
339func (e reportedError) Error() string {
343func (e reportedError) Unwrap() error {
347func (c *Client) tlsConfig() *tls.Config {
348 // We always manage verification ourselves: We need to report in detail about
349 // failures. And we may have to verify both PKIX and DANE, record errors for
350 // each, and possibly ignore the errors.
352 verifyConnection := func(cs tls.ConnectionState) error {
353 // Collect verification errors. If there are none at the end, TLS validation
354 // succeeded. We may find validation problems below, record them for a TLS report
355 // but continue due to policies. We track the TLS reporting result in this
356 // function, wrapping errors in a reportedError.
357 var daneErr, pkixErr error
359 // DANE verification.
360 // daneRecords can be non-nil and empty, that's intended.
361 if c.daneRecords != nil {
362 verified, record, err := dane.Verify(c.log.Logger, c.daneRecords, cs, c.remoteHostname, c.daneMoreHostnames, c.rootCAs)
363 c.log.Debugx("dane verification", err, slog.Bool("verified", verified), slog.Any("record", record))
365 if c.daneVerifiedRecord != nil {
366 *c.daneVerifiedRecord = record
369 // Track error for reports.
370 // 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
371 fd := c.tlsrptFailureDetails(tlsrpt.ResultValidationFailure, "dane-no-match")
373 // 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.
375 // We may have encountered errors while evaluation some of the TLSA records.
376 fd.FailureReasonCode += "+errors"
378 c.hostResult.Add(0, 0, fd)
380 if c.ignoreTLSVerifyErrors {
381 // We ignore the failure and continue the connection.
382 c.log.Infox("verifying dane failed, continuing with connection", err)
383 MetricTLSRequiredNoIgnored.IncLabels("daneverification")
385 // This connection will fail.
386 daneErr = dane.ErrNoMatch
391 // PKIX verification.
392 opts := x509.VerifyOptions{
393 DNSName: cs.ServerName,
394 Intermediates: x509.NewCertPool(),
397 for _, cert := range cs.PeerCertificates[1:] {
398 opts.Intermediates.AddCert(cert)
400 if _, err := cs.PeerCertificates[0].Verify(opts); err != nil {
401 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
402 fd := c.tlsrptFailureDetails(resultType, reasonCode)
403 c.recipientDomainResult.Add(0, 0, fd)
405 if c.tlsVerifyPKIX && !c.ignoreTLSVerifyErrors {
410 if daneErr != nil && pkixErr != nil {
411 return reportedError{errors.Join(daneErr, pkixErr)}
412 } else if daneErr != nil {
413 return reportedError{daneErr}
414 } else if pkixErr != nil {
415 return reportedError{pkixErr}
421 ServerName: c.remoteHostname.ASCII, // For SNI.
422 // todo: possibly accept older TLS versions for TLSOpportunistic? or would our private key be at risk?
424 InsecureSkipVerify: true, // VerifyConnection below is called and will do all verification.
425 VerifyConnection: verifyConnection,
429// xbotchf generates a temporary error and marks the client as botched. e.g. for
430// i/o errors or invalid protocol messages.
431func (c *Client) xbotchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) {
432 panic(c.botchf(code, secode, firstLine, moreLines, format, args...))
435// botchf generates a temporary error and marks the client as botched. e.g. for
436// i/o errors or invalid protocol messages.
437func (c *Client) botchf(code int, secode string, firstLine string, moreLines []string, format string, args ...any) error {
439 return c.errorf(false, code, secode, firstLine, moreLines, format, args...)
442func (c *Client) errorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) error {
447 return Error{permanent, code, secode, cmd, firstLine, moreLines, fmt.Errorf(format, args...)}
450func (c *Client) xerrorf(permanent bool, code int, secode, firstLine string, moreLines []string, format string, args ...any) {
451 panic(c.errorf(permanent, code, secode, firstLine, moreLines, format, args...))
454// timeoutWriter passes each Write on to conn after setting a write deadline on conn based on
456type timeoutWriter struct {
458 timeout time.Duration
462func (w timeoutWriter) Write(buf []byte) (int, error) {
463 if err := w.conn.SetWriteDeadline(time.Now().Add(w.timeout)); err != nil {
464 w.log.Errorx("setting write deadline", err)
467 return w.conn.Write(buf)
470var bufs = moxio.NewBufpool(8, 2*1024)
472func (c *Client) readline() (string, error) {
473 // todo: could have per-operation timeouts. and rfc suggests higher minimum timeouts.
../rfc/5321:3610
474 if err := c.conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
475 c.log.Errorx("setting read deadline", err)
478 line, err := bufs.Readline(c.log, c.r)
480 // See if this is a TLS alert from remote, and one other than 0 (which notifies
481 // that the connection is being closed. If so, we register a TLS connection
482 // failure. This handles TLS alerts that happen just after a successful handshake.
483 var netErr *net.OpError
484 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 {
485 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
486 // We count -1 success to compensate for the assumed success right after the handshake.
487 c.tlsResultAddFailureDetails(-1, 1, c.tlsrptFailureDetails(resultType, reasonCode))
490 return line, c.botchf(0, "", "", nil, "%s: %w", strings.Join(c.cmds, ","), err)
492 c.firstReadAfterHandshake = false
496func (c *Client) xtrace(level slog.Level) func() {
502 c.tr.SetTrace(mlog.LevelTrace)
503 c.tw.SetTrace(mlog.LevelTrace)
507func (c *Client) xwritelinef(format string, args ...any) {
508 c.xbwritelinef(format, args...)
512func (c *Client) xwriteline(line string) {
517func (c *Client) xbwritelinef(format string, args ...any) {
518 c.xbwriteline(fmt.Sprintf(format, args...))
521func (c *Client) xbwriteline(line string) {
522 _, err := fmt.Fprintf(c.w, "%s\r\n", line)
524 c.xbotchf(0, "", "", nil, "write: %w", err)
528func (c *Client) xflush() {
531 c.xbotchf(0, "", "", nil, "writes: %w", err)
535// read response, possibly multiline, with supporting extended codes based on configuration in client.
536func (c *Client) xread() (code int, secode, firstLine string, moreLines []string) {
538 code, secode, firstLine, moreLines, err = c.read()
545func (c *Client) read() (code int, secode, firstLine string, moreLines []string, rerr error) {
546 code, secode, _, firstLine, moreLines, _, rerr = c.readecode(c.extEcodes)
550// read response, possibly multiline.
551// if ecodes, extended codes are parsed.
552func (c *Client) readecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string, rerr error) {
555 co, sec, text, line, last, err := c.read1(ecodes)
559 } else if line != "" {
560 moreLines = append(moreLines, line)
562 moreTexts = append(moreTexts, text)
569 if code != 0 && co != code {
571 err := c.botchf(0, "", firstLine, moreLines, "%w: multiline response with different codes, previous %d, last %d", ErrProtocol, code, co)
572 return 0, "", "", "", nil, nil, err
576 if code != smtp.C334ContinueAuth {
580 // We only keep the last, so we're not creating new slices all the time.
585 MetricCommands.ObserveLabels(float64(time.Since(c.cmdStart))/float64(time.Second), cmd, fmt.Sprintf("%d", co), sec)
586 c.log.Debug("smtpclient command result",
587 slog.String("cmd", cmd),
588 slog.Int("code", co),
589 slog.String("secode", sec),
590 slog.Duration("duration", time.Since(c.cmdStart)))
592 return co, sec, text, firstLine, moreLines, moreTexts, nil
597func (c *Client) xreadecode(ecodes bool) (code int, secode, lastText, firstLine string, moreLines, moreTexts []string) {
599 code, secode, lastText, firstLine, moreLines, moreTexts, err = c.readecode(ecodes)
606// read single response line.
607// if ecodes, extended codes are parsed.
608func (c *Client) read1(ecodes bool) (code int, secode, text, line string, last bool, rerr error) {
609 line, rerr = c.readline()
614 for ; i < len(line) && line[i] >= '0' && line[i] <= '9'; i++ {
617 rerr = c.botchf(0, "", line, nil, "%w: expected response code: %s", ErrProtocol, line)
620 v, err := strconv.ParseInt(line[:i], 10, 32)
622 rerr = c.botchf(0, "", line, nil, "%w: bad response code (%s): %s", ErrProtocol, err, line)
628 if strings.HasPrefix(s, "-") || strings.HasPrefix(s, " ") {
635 rerr = c.botchf(0, "", line, nil, "%w: expected space or dash after response code: %s", ErrProtocol, line)
640 secode, s = parseEcode(major, s)
643 return code, secode, s, line, last, nil
646func parseEcode(major int, s string) (secode string, remain string) {
649 take := func(need bool, a, b byte) bool {
650 if !bad && o < len(s) && s[o] >= a && s[o] <= b {
657 digit := func(need bool) bool {
658 return take(need, '0', '9')
661 return take(true, '.', '.')
675 take(false, ' ', ' ')
676 if bad || int(s[0])-int('0') != major {
682func (c *Client) recover(rerr *error) {
687 cerr, ok := x.(Error)
695func (c *Client) hello(ctx context.Context, tlsMode TLSMode, ehloHostname dns.Domain, auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
696 defer c.recover(&rerr)
698 // perform EHLO handshake, falling back to HELO if server does not appear to
700 hello := func(heloOK bool) {
701 // Write EHLO and parse the supported extensions.
704 c.cmdStart = time.Now()
706 c.xwritelinef("EHLO %s", ehloHostname.ASCII)
707 code, _, _, firstLine, moreLines, moreTexts := c.xreadecode(false)
711 case smtp.C500BadSyntax, smtp.C501BadParamSyntax, smtp.C502CmdNotImpl, smtp.C503BadCmdSeq, smtp.C504ParamNotImpl:
713 c.xerrorf(true, code, "", firstLine, moreLines, "%w: remote claims ehlo is not supported", ErrProtocol)
717 c.cmdStart = time.Now()
718 c.xwritelinef("HELO %s", ehloHostname.ASCII)
719 code, _, _, firstLine, _, _ = c.xreadecode(false)
720 if code != smtp.C250Completed {
721 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250 to HELO, got %d", ErrStatus, code)
724 case smtp.C250Completed:
726 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 250, got %d", ErrStatus, code)
728 for _, s := range moreTexts {
730 s = strings.ToUpper(strings.TrimSpace(s))
734 case "ENHANCEDSTATUSCODES":
739 c.extPipelining = true
741 c.extRequireTLS = true
744 if s == "SMTPUTF8" || strings.HasPrefix(s, "SMTPUTF8 ") {
746 } else if strings.HasPrefix(s, "SIZE ") {
749 if v, err := strconv.ParseInt(s[len("SIZE "):], 10, 64); err == nil {
752 } else if strings.HasPrefix(s, "AUTH ") {
753 c.extAuthMechanisms = strings.Split(s[len("AUTH "):], " ")
754 } else if strings.HasPrefix(s, "LIMITS ") {
755 c.ExtLimits, c.ExtLimitMailMax, c.ExtLimitRcptMax, c.ExtLimitRcptDomainMax = parseLimits([]byte(s[len("LIMITS"):]))
762 c.cmds = []string{"(greeting)"}
763 c.cmdStart = time.Now()
764 code, _, _, firstLine, moreLines, _ := c.xreadecode(false)
765 if code != smtp.C220ServiceReady {
766 c.xerrorf(code/100 == 5, code, "", firstLine, moreLines, "%w: expected 220, got %d", ErrStatus, code)
769 _, c.remoteHelo, _ = strings.Cut(firstLine, " ")
771 // Write EHLO, falling back to HELO if server doesn't appear to support it.
774 // Attempt TLS if remote understands STARTTLS and we aren't doing immediate TLS or if caller requires it.
775 if c.extStartTLS && tlsMode == TLSOpportunistic || tlsMode == TLSRequiredStartTLS {
776 c.log.Debug("starting tls client", slog.Any("tlsmode", tlsMode), slog.Any("servername", c.remoteHostname))
777 c.cmds[0] = "starttls"
778 c.cmdStart = time.Now()
779 c.xwritelinef("STARTTLS")
780 code, secode, firstLine, _ := c.xread()
782 if code != smtp.C220ServiceReady {
783 c.tlsResultAddFailureDetails(0, 1, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, fmt.Sprintf("smtp-starttls-reply-code-%d", code)))
784 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: STARTTLS: got %d, expected 220", ErrTLS, code)
787 // We don't want to do TLS on top of c.r because it also prints protocol traces: We
788 // don't want to log the TLS stream. So we'll do TLS on the underlying connection,
789 // but make sure any bytes already read and in the buffer are used for the TLS
792 if n := c.r.Buffered(); n > 0 {
793 conn = &moxio.PrefixConn{
794 PrefixReader: io.LimitReader(c.r, int64(n)),
799 tlsConfig := c.tlsConfig()
800 nconn := tls.Client(conn, tlsConfig)
803 nctx, cancel := context.WithTimeout(ctx, time.Minute)
805 err := nconn.HandshakeContext(nctx)
807 // For each STARTTLS failure, we track a failed TLS session. For deliveries with
808 // multiple MX targets, we may add multiple failures, and delivery may succeed with
810 c.tlsResultAdd(0, 1, err)
811 c.xerrorf(false, 0, "", "", nil, "%w: STARTTLS TLS handshake: %s", ErrTLS, err)
813 c.firstReadAfterHandshake = true
815 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
816 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.
817 c.r = bufio.NewReader(c.tr)
818 c.w = bufio.NewWriter(c.tw)
820 tlsversion, ciphersuite := moxio.TLSInfo(nconn)
821 c.log.Debug("starttls client handshake done",
822 slog.Any("tlsmode", tlsMode),
823 slog.Bool("verifypkix", c.tlsVerifyPKIX),
824 slog.Bool("verifydane", c.daneRecords != nil),
825 slog.Bool("ignoretlsverifyerrors", c.ignoreTLSVerifyErrors),
826 slog.String("tls", tlsversion),
827 slog.String("ciphersuite", ciphersuite),
828 slog.Any("servername", c.remoteHostname),
829 slog.Any("danerecord", c.daneVerifiedRecord))
832 c.tlsResultAdd(1, 0, nil)
835 } else if tlsMode == TLSOpportunistic {
837 c.tlsResultAddFailureDetails(0, 0, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, ""))
846// parse text after "LIMITS", including leading space.
847func parseLimits(b []byte) (map[string]string, int, int, int) {
850 // Read next " name=value".
851 pair := func() ([]byte, []byte) {
852 if o >= len(b) || b[o] != ' ' {
860 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' {
867 if ns == es || o >= len(b) || b[o] != '=' {
874 if c > 0x20 && c < 0x7f && c != ';' {
883 return b[ns:es], b[vs:o]
885 limits := map[string]string{}
886 var mailMax, rcptMax, rcptDomainMax int
888 name, value := pair()
893 k := strings.ToUpper(string(name))
894 if _, ok := limits[k]; ok {
895 // Not specified, but we treat duplicates as error.
898 limits[k] = string(value)
899 // For individual value syntax errors, we skip that value, leaving the default 0.
901 switch string(name) {
903 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
907 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
910 case "RCPTDOMAINMAX":
911 if v, err := strconv.Atoi(string(value)); err == nil && v > 0 && len(value) <= 6 {
916 return limits, mailMax, rcptMax, rcptDomainMax
919func addrIP(addr net.Addr) string {
920 if t, ok := addr.(*net.TCPAddr); ok {
923 host, _, _ := net.SplitHostPort(addr.String())
924 ip := net.ParseIP(host)
926 return "" // For pipe during tests.
931// tlsrptFailureDetails returns FailureDetails with connection details (such as
932// IP addresses) for inclusion in a TLS report.
933func (c *Client) tlsrptFailureDetails(resultType tlsrpt.ResultType, reasonCode string) tlsrpt.FailureDetails {
934 return tlsrpt.FailureDetails{
935 ResultType: resultType,
936 SendingMTAIP: addrIP(c.origConn.LocalAddr()),
937 ReceivingMXHostname: c.remoteHostname.ASCII,
938 ReceivingMXHelo: c.remoteHelo,
939 ReceivingIP: addrIP(c.origConn.RemoteAddr()),
940 FailedSessionCount: 1,
941 FailureReasonCode: reasonCode,
945// tlsResultAdd adds TLS success/failure to all results.
946func (c *Client) tlsResultAdd(success, failure int64, err error) {
947 // Only track failure if not already done so in tls.Config.VerifyConnection.
948 var fds []tlsrpt.FailureDetails
949 var repErr reportedError
950 if err != nil && !errors.As(err, &repErr) {
951 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
952 fd := c.tlsrptFailureDetails(resultType, reasonCode)
953 fds = []tlsrpt.FailureDetails{fd}
955 c.tlsResultAddFailureDetails(success, failure, fds...)
958func (c *Client) tlsResultAddFailureDetails(success, failure int64, fds ...tlsrpt.FailureDetails) {
959 c.recipientDomainResult.Add(success, failure, fds...)
960 c.hostResult.Add(success, failure, fds...)
964func (c *Client) auth(auth func(mechanisms []string, cs *tls.ConnectionState) (sasl.Client, error)) (rerr error) {
965 defer c.recover(&rerr)
968 c.cmdStart = time.Now()
970 mechanisms := make([]string, len(c.extAuthMechanisms))
971 for i, m := range c.extAuthMechanisms {
972 mechanisms[i] = strings.ToUpper(m)
974 a, err := auth(mechanisms, c.TLSConnectionState())
976 c.xerrorf(true, 0, "", "", nil, "get authentication mechanism: %s, server supports %s", err, strings.Join(c.extAuthMechanisms, ", "))
978 c.xerrorf(true, 0, "", "", nil, "no matching authentication mechanisms, server supports %s", strings.Join(c.extAuthMechanisms, ", "))
980 name, cleartextCreds := a.Info()
982 abort := func() (int, string, string, []string) {
987 code, secode, firstLine, moreLines := c.xread()
988 if code != smtp.C501BadParamSyntax {
991 return code, secode, firstLine, moreLines
994 toserver, last, err := a.Next(nil)
996 c.xerrorf(false, 0, "", "", nil, "initial step in auth mechanism %s: %w", name, err)
999 defer c.xtrace(mlog.LevelTraceauth)()
1001 if toserver == nil {
1002 c.xwriteline("AUTH " + name)
1003 } else if len(toserver) == 0 {
1006 c.xwriteline("AUTH " + name + " " + base64.StdEncoding.EncodeToString(toserver))
1009 if cleartextCreds && last {
1010 c.xtrace(mlog.LevelTrace) // Restore.
1013 code, secode, lastText, firstLine, moreLines, _ := c.xreadecode(last)
1014 if code == smtp.C235AuthSuccess {
1016 c.xerrorf(false, code, secode, firstLine, moreLines, "server completed authentication earlier than client expected")
1019 } else if code == smtp.C334ContinueAuth {
1021 c.xerrorf(false, code, secode, firstLine, moreLines, "server requested unexpected continuation of authentication")
1023 if len(moreLines) > 0 {
1025 c.xerrorf(false, code, secode, firstLine, moreLines, "server responded with multiline contination")
1027 fromserver, err := base64.StdEncoding.DecodeString(lastText)
1030 c.xerrorf(false, code, secode, firstLine, moreLines, "malformed base64 data in authentication continuation response")
1032 toserver, last, err = a.Next(fromserver)
1034 // For failing SCRAM, the client stops due to message about invalid proof. The
1035 // server still sends an authentication result (it probably should send 501
1037 xcode, xsecode, xfirstLine, xmoreLines := abort()
1038 c.xerrorf(false, xcode, xsecode, xfirstLine, xmoreLines, "client aborted authentication: %w", err)
1040 c.xwriteline(base64.StdEncoding.EncodeToString(toserver))
1042 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "unexpected response during authentication, expected 334 continue or 235 auth success")
1047// Supports8BITMIME returns whether the SMTP server supports the 8BITMIME
1048// extension, needed for sending data with non-ASCII bytes.
1049func (c *Client) Supports8BITMIME() bool {
1050 return c.ext8bitmime
1053// SupportsSMTPUTF8 returns whether the SMTP server supports the SMTPUTF8
1054// extension, needed for sending messages with UTF-8 in headers or in an (SMTP)
1056func (c *Client) SupportsSMTPUTF8() bool {
1057 return c.extSMTPUTF8
1060// SupportsStartTLS returns whether the SMTP server supports the STARTTLS
1062func (c *Client) SupportsStartTLS() bool {
1063 return c.extStartTLS
1066// SupportsRequireTLS returns whether the SMTP server supports the REQUIRETLS
1067// extension. The REQUIRETLS extension is only announced after enabling
1069func (c *Client) SupportsRequireTLS() bool {
1070 return c.extRequireTLS
1073// TLSConnectionState returns TLS details if TLS is enabled, and nil otherwise.
1074func (c *Client) TLSConnectionState() *tls.ConnectionState {
1075 if tlsConn, ok := c.conn.(*tls.Conn); ok {
1076 cs := tlsConn.ConnectionState()
1082// Deliver attempts to deliver a message to a mail server.
1084// mailFrom must be an email address, or empty in case of a DSN. rcptTo must be
1087// If the message contains bytes with the high bit set, req8bitmime must be true. If
1088// set, the remote server must support the 8BITMIME extension or delivery will
1091// If the message is internationalized, e.g. when headers contain non-ASCII
1092// character, or when UTF-8 is used in a localpart, reqSMTPUTF8 must be true. If set,
1093// the remote server must support the SMTPUTF8 extension or delivery will fail.
1095// If requireTLS is true, the remote server must support the REQUIRETLS
1096// extension, or delivery will fail.
1098// Deliver uses the following SMTP extensions if the remote server supports them:
1099// 8BITMIME, SMTPUTF8, SIZE, PIPELINING, ENHANCEDSTATUSCODES, STARTTLS.
1101// Returned errors can be of type Error, one of the Err-variables in this package
1102// or other underlying errors, e.g. for i/o. Use errors.Is to check.
1103func (c *Client) Deliver(ctx context.Context, mailFrom string, rcptTo string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rerr error) {
1104 _, err := c.DeliverMultiple(ctx, mailFrom, []string{rcptTo}, msgSize, msg, req8bitmime, reqSMTPUTF8, requireTLS)
1108var errNoRecipientsPipelined = errors.New("no recipients accepted in pipelined transaction")
1109var errNoRecipients = errors.New("no recipients accepted in transaction")
1111// DeliverMultiple is like Deliver, but attempts to deliver a message to multiple
1112// recipients. Errors about the entire transaction, such as i/o errors or error
1113// responses to the MAIL FROM or DATA commands, are returned by a non-nil rerr. If
1114// rcptTo has a single recipient, an error to the RCPT TO command is returned in
1115// rerr instead of rcptResps. Otherwise, the SMTP response for each recipient is
1116// returned in rcptResps.
1118// The caller should take extLimit* into account when sending. And recognize
1119// recipient response code "452" to mean that a recipient limit was reached,
1120// another transaction can be attempted immediately after instead of marking the
1121// delivery attempt as failed. Also code "552" must be treated like temporary error
1122// code "452" for historic reasons.
1123func (c *Client) DeliverMultiple(ctx context.Context, mailFrom string, rcptTo []string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rcptResps []Response, rerr error) {
1124 defer c.recover(&rerr)
1126 if len(rcptTo) == 0 {
1127 return nil, fmt.Errorf("need at least one recipient")
1130 if c.origConn == nil {
1131 return nil, ErrClosed
1132 } else if c.botched {
1133 return nil, ErrBotched
1134 } else if c.needRset {
1135 if err := c.Reset(); err != nil {
1140 if !c.ext8bitmime && req8bitmime {
1141 // Temporary error, e.g. OpenBSD spamd does not announce 8bitmime support, but once
1142 // you get through, the mail server behind it probably does. Just needs a few
1144 c.xerrorf(false, 0, "", "", nil, "%w", Err8bitmimeUnsupported)
1146 if !c.extSMTPUTF8 && reqSMTPUTF8 {
1148 c.xerrorf(false, 0, "", "", nil, "%w", ErrSMTPUTF8Unsupported)
1150 if !c.extRequireTLS && requireTLS {
1151 c.xerrorf(false, 0, "", "", nil, "%w", ErrRequireTLSUnsupported)
1155 if c.extSize && c.maxSize > 0 && msgSize > c.maxSize {
1156 c.xerrorf(true, 0, "", "", nil, "%w: message is %d bytes, remote has a %d bytes maximum size", ErrSize, msgSize, c.maxSize)
1159 var mailSize, bodyType string
1161 mailSize = fmt.Sprintf(" SIZE=%d", msgSize)
1165 bodyType = " BODY=8BITMIME"
1167 bodyType = " BODY=7BIT"
1170 var smtputf8Arg string
1173 smtputf8Arg = " SMTPUTF8"
1175 var requiretlsArg string
1178 requiretlsArg = " REQUIRETLS"
1185 lineMailFrom := fmt.Sprintf("MAIL FROM:<%s>%s%s%s%s", mailFrom, mailSize, bodyType, smtputf8Arg, requiretlsArg)
1187 // We are going into a transaction. We'll clear this when done.
1190 if c.extPipelining {
1191 c.cmds = make([]string, 1+len(rcptTo)+1)
1192 c.cmds[0] = "mailfrom"
1193 for i := range rcptTo {
1194 c.cmds[1+i] = "rcptto"
1196 c.cmds[len(c.cmds)-1] = "data"
1197 c.cmdStart = time.Now()
1199 // Write and read in separte goroutines. Otherwise, writing a large recipient list
1200 // could block when a server doesn't read more commands before we read their
1202 errc := make(chan error, 1)
1203 // Make sure we don't return before we're done writing to the connection.
1211 b.WriteString(lineMailFrom)
1212 b.WriteString("\r\n")
1213 for _, rcpt := range rcptTo {
1214 b.WriteString("RCPT TO:<")
1216 b.WriteString(">\r\n")
1218 b.WriteString("DATA\r\n")
1219 _, err := c.w.Write(b.Bytes())
1226 // Read response to MAIL FROM.
1227 mfcode, mfsecode, mffirstLine, mfmoreLines := c.xread()
1229 // We read the response to RCPT TOs and DATA without panic on read error. Servers
1230 // may be aborting the connection after a failed MAIL FROM, e.g. outlook when it
1231 // has blocklisted your IP. We don't want the read for the response to RCPT TO to
1232 // cause a read error as it would result in an unhelpful error message and a
1233 // temporary instead of permanent error code.
1235 // Read responses to RCPT TO.
1236 rcptResps = make([]Response, len(rcptTo))
1238 for i := 0; i < len(rcptTo); i++ {
1239 code, secode, firstLine, moreLines, err := c.read()
1241 permanent := code/100 == 5 && code != smtp.C552MailboxFull
1242 rcptResps[i] = Response{permanent, code, secode, "rcptto", firstLine, moreLines, err}
1243 if code == smtp.C250Completed {
1248 // Read response to DATA.
1249 datacode, datasecode, datafirstLine, datamoreLines, dataerr := c.read()
1254 // If MAIL FROM failed, it's an error for the entire transaction. We may have been
1256 if mfcode != smtp.C250Completed {
1257 if writeerr != nil || dataerr != nil {
1260 c.xerrorf(mfcode/100 == 5, mfcode, mfsecode, mffirstLine, mfmoreLines, "%w: got %d, expected 2xx", ErrStatus, mfcode)
1263 // If there was an i/o error writing the commands, there is no point continuing.
1264 if writeerr != nil {
1265 c.xbotchf(0, "", "", nil, "writing pipelined mail/rcpt/data: %w", writeerr)
1268 // If the data command had an i/o or protocol error, it's also a failure for the
1269 // entire transaction.
1274 // If we didn't have any successful recipient, there is no point in continuing.
1276 // Servers may return success for a DATA without valid recipients. Write a dot to
1277 // end DATA and restore the connection to a known state.
1279 if datacode == smtp.C354Continue {
1280 _, doterr := fmt.Fprintf(c.w, ".\r\n")
1282 doterr = c.w.Flush()
1285 _, _, _, _, doterr = c.read()
1292 if len(rcptTo) == 1 {
1293 panic(Error(rcptResps[0]))
1295 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipientsPipelined)
1298 if datacode != smtp.C354Continue {
1299 c.xerrorf(datacode/100 == 5, datacode, datasecode, datafirstLine, datamoreLines, "%w: got %d, expected 354", ErrStatus, datacode)
1303 c.cmds[0] = "mailfrom"
1304 c.cmdStart = time.Now()
1305 c.xwriteline(lineMailFrom)
1306 code, secode, firstLine, moreLines := c.xread()
1307 if code != smtp.C250Completed {
1308 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1311 rcptResps = make([]Response, len(rcptTo))
1313 for i, rcpt := range rcptTo {
1314 c.cmds[0] = "rcptto"
1315 c.cmdStart = time.Now()
1316 c.xwriteline(fmt.Sprintf("RCPT TO:<%s>", rcpt))
1317 code, secode, firstLine, moreLines = c.xread()
1318 if i > 0 && (code == smtp.C452StorageFull || code == smtp.C552MailboxFull) {
1319 // Remote doesn't accept more recipients for this transaction. Don't send more, give
1320 // remaining recipients the same error result.
1321 for j := i; j < len(rcptTo); j++ {
1322 rcptResps[j] = Response{false, code, secode, "rcptto", firstLine, moreLines, fmt.Errorf("no more recipients accepted in transaction")}
1327 if code == smtp.C250Completed {
1330 err = fmt.Errorf("%w: got %d, expected 2xx", ErrStatus, code)
1332 rcptResps[i] = Response{code/100 == 5, code, secode, "rcptto", firstLine, moreLines, err}
1336 if len(rcptTo) == 1 {
1337 panic(Error(rcptResps[0]))
1339 c.xerrorf(false, 0, "", "", nil, "%w", errNoRecipients)
1343 c.cmdStart = time.Now()
1344 c.xwriteline("DATA")
1345 code, secode, firstLine, moreLines = c.xread()
1346 if code != smtp.C354Continue {
1347 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 354", ErrStatus, code)
1351 // For a DATA write, the suggested timeout is 3 minutes, we use 30 seconds for all
1353 defer c.xtrace(mlog.LevelTracedata)()
1354 err := smtp.DataWrite(c.w, msg)
1356 c.xbotchf(0, "", "", nil, "writing message as smtp data: %w", err)
1359 c.xtrace(mlog.LevelTrace) // Restore.
1360 code, secode, firstLine, moreLines := c.xread()
1361 if code != smtp.C250Completed {
1362 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1369// Reset sends an SMTP RSET command to reset the message transaction state. Deliver
1370// automatically sends it if needed.
1371func (c *Client) Reset() (rerr error) {
1372 if c.origConn == nil {
1374 } else if c.botched {
1378 defer c.recover(&rerr)
1382 c.cmdStart = time.Now()
1383 c.xwriteline("RSET")
1384 code, secode, firstLine, moreLines := c.xread()
1385 if code != smtp.C250Completed {
1386 c.xerrorf(code/100 == 5, code, secode, firstLine, moreLines, "%w: got %d, expected 2xx", ErrStatus, code)
1392// Botched returns whether this connection is botched, e.g. a protocol error
1393// occurred and the connection is in unknown state, and cannot be used for message
1395func (c *Client) Botched() bool {
1396 return c.botched || c.origConn == nil
1399// Close cleans up the client, closing the underlying connection.
1401// If the connection is initialized and not botched, a QUIT command is sent and the
1402// response read with a short timeout before closing the underlying connection.
1404// Close returns any error encountered during QUIT and closing.
1405func (c *Client) Close() (rerr error) {
1406 if c.origConn == nil {
1410 defer c.recover(&rerr)
1415 c.cmdStart = time.Now()
1416 c.xwriteline("QUIT")
1417 if err := c.conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
1418 c.log.Infox("setting read deadline for reading quit response", err)
1419 } else if _, err := bufs.Readline(c.log, c.r); err != nil {
1420 rerr = fmt.Errorf("reading response to quit command: %v", err)
1421 c.log.Debugx("reading quit response", err)
1425 err := c.origConn.Close()
1426 if c.conn != c.origConn {
1427 // This is the TLS connection. Close will attempt to write a close notification.
1428 // But it will fail quickly because the underlying socket was closed.
1439// Conn returns the connection with initialized SMTP session. Once the caller uses
1440// this connection it is in control, and responsible for closing the connection,
1441// and other functions on the client must not be called anymore.
1442func (c *Client) Conn() (net.Conn, error) {
1443 if err := c.conn.SetDeadline(time.Time{}); err != nil {
1444 return nil, fmt.Errorf("clearing io deadlines: %w", err)