1// Package smtpclient is an SMTP client, used by the queue for sending outgoing messages.
19 "github.com/prometheus/client_golang/prometheus"
20 "github.com/prometheus/client_golang/prometheus/promauto"
22 "github.com/mjl-/adns"
24 "github.com/mjl-/mox/dane"
25 "github.com/mjl-/mox/dns"
26 "github.com/mjl-/mox/metrics"
27 "github.com/mjl-/mox/mlog"
28 "github.com/mjl-/mox/mox-"
29 "github.com/mjl-/mox/moxio"
30 "github.com/mjl-/mox/sasl"
31 "github.com/mjl-/mox/smtp"
32 "github.com/mjl-/mox/tlsrpt"
35// 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
38 metricCommands = promauto.NewHistogramVec(
39 prometheus.HistogramOpts{
40 Name: "mox_smtpclient_command_duration_seconds",
41 Help: "SMTP client command duration and result codes in seconds.",
42 Buckets: []float64{0.001, 0.005, 0.01, 0.05, 0.100, 0.5, 1, 5, 10, 20, 30, 60, 120},
50 metricTLSRequiredNoIgnored = promauto.NewCounterVec(
51 prometheus.CounterOpts{
52 Name: "mox_smtpclient_tlsrequiredno_ignored_total",
53 Help: "Connection attempts with TLS policy findings ignored due to message with TLS-Required: No header. Does not cover case where TLS certificate cannot be PKIX-verified.",
56 "ignored", // daneverification (no matching tlsa record)
62 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.
63 Err8bitmimeUnsupported = errors.New("remote smtp server does not implement 8bitmime extension, required by message")
64 ErrSMTPUTF8Unsupported = errors.New("remote smtp server does not implement smtputf8 extension, required by message")
65 ErrRequireTLSUnsupported = errors.New("remote smtp server does not implement requiretls extension, required for delivery")
66 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.
67 ErrProtocol = errors.New("smtp protocol error") // After a malformed SMTP response or inconsistent multi-line response.
68 ErrTLS = errors.New("tls error") // E.g. handshake failure, or hostname verification was required and failed.
69 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.
70 ErrClosed = errors.New("client is closed")
73// TLSMode indicates if TLS must, should or must not be used.
77 // TLS immediately ("implicit TLS"), directly starting TLS on the TCP connection,
78 // so not using STARTTLS. Whether PKIX and/or DANE is verified is specified
80 TLSImmediate TLSMode = "immediate"
82 // Required TLS with STARTTLS for SMTP servers. The STARTTLS command is always
83 // executed, even if the server does not announce support.
84 // Whether PKIX and/or DANE is verified is specified separately.
85 TLSRequiredStartTLS TLSMode = "requiredstarttls"
87 // Use TLS with STARTTLS if remote claims to support it.
88 TLSOpportunistic TLSMode = "opportunistic"
90 // TLS must not be attempted, e.g. due to earlier TLS handshake error.
91 TLSSkip TLSMode = "skip"
94// Client is an SMTP client that can deliver messages to a mail server.
96// Use New to make a new client.
98 // OrigConn is the original (TCP) connection. We'll read from/write to conn, which
99 // can be wrapped in a tls.Client. We close origConn instead of conn because
100 // closing the TLS connection would send a TLS close notification, which may block
101 // for 5s if the server isn't reading it (because it is also sending it).
105 ignoreTLSVerifyErrors bool
106 rootCAs *x509.CertPool
107 remoteHostname dns.Domain // TLS with SNI and name verification.
108 daneRecords []adns.TLSA // For authenticating (START)TLS connection.
109 daneMoreHostnames []dns.Domain // Additional allowed names in TLS certificate for DANE-TA.
110 daneVerifiedRecord *adns.TLSA // If non-nil, then will be set to verified DANE record if any.
112 // TLS connection success/failure are added. These are always non-nil, regardless
113 // of what was passed in opts. It lets us unconditionally dereference them.
114 recipientDomainResult *tlsrpt.Result // Either "sts" or "no-policy-found".
115 hostResult *tlsrpt.Result // Either "dane" or "no-policy-found".
119 tr *moxio.TraceReader // Kept for changing trace levels between cmd/auth/data.
120 tw *moxio.TraceWriter
122 lastlog time.Time // For adding delta timestamps between log lines.
123 cmds []string // Last or active command, for generating errors and metrics.
124 cmdStart time.Time // Start of command.
125 tls bool // Whether connection is TLS protected.
126 firstReadAfterHandshake bool // To detect TLS alert error from remote just after handshake.
128 botched bool // If set, protocol is out of sync and no further commands can be sent.
129 needRset bool // If set, a new delivery requires an RSET command.
131 remoteHelo string // From 220 greeting line.
132 extEcodes bool // Remote server supports sending extended error codes.
133 extStartTLS bool // Remote server supports STARTTLS.
135 extSize bool // Remote server supports SIZE parameter.
136 maxSize int64 // Max size of email message.
137 extPipelining bool // Remote server supports command pipelining.
138 extSMTPUTF8 bool // Remote server supports SMTPUTF8 extension.
139 extAuthMechanisms []string // Supported authentication mechanisms.
140 extRequireTLS bool // Remote supports REQUIRETLS extension.
143// Error represents a failure to deliver a message.
145// Code, Secode, Command and Line are only set for SMTP-level errors, and are zero
148 // Whether failure is permanent, typically because of 5xx response.
150 // SMTP response status, e.g. 2xx for success, 4xx for transient error and 5xx for
151 // permanent failure.
153 // Short enhanced status, minus first digit and dot. Can be empty, e.g. for io
154 // errors or if remote does not send enhanced status codes. If remote responds with
155 // "550 5.7.1 ...", the Secode will be "7.1".
157 // SMTP command causing failure.
159 // For errors due to SMTP responses, the full SMTP line excluding CRLF that caused
160 // the error. Typically the last line read.
162 // Underlying error, e.g. one of the Err variables in this package, or io errors.
166// Unwrap returns the underlying Err.
167func (e Error) Unwrap() error {
171// Error returns a readable error string.
172func (e Error) Error() string {
175 s = e.Err.Error() + ", "
188// Opts influence behaviour of Client.
190 // If auth is non-empty, authentication will be done with the first algorithm
191 // supported by the server. If none of the algorithms are supported, an error is
195 DANERecords []adns.TLSA // If not nil, DANE records to verify.
196 DANEMoreHostnames []dns.Domain // For use with DANE, where additional certificate host names are allowed.
197 DANEVerifiedRecord *adns.TLSA // If non-empty, set to the DANE record that verified the TLS connection.
199 // If set, TLS verification errors (for DANE or PKIX) are ignored. Useful for
200 // delivering messages with message header "TLS-Required: No".
201 // Certificates are still verified, and results are still tracked for TLS
202 // reporting, but the connections will continue.
203 IgnoreTLSVerifyErrors bool
205 // If not nil, used instead of the system default roots for TLS PKIX verification.
206 RootCAs *x509.CertPool
208 // TLS verification successes/failures is added to these TLS reporting results.
209 // Once the STARTTLS handshake is attempted, a successful/failed connection is
211 RecipientDomainResult *tlsrpt.Result // MTA-STS or no policy.
212 HostResult *tlsrpt.Result // DANE or no policy.
215// New initializes an SMTP session on the given connection, returning a client that
216// can be used to deliver messages.
218// New optionally starts TLS (for submission), reads the server greeting,
219// identifies itself with a HELO or EHLO command, initializes TLS with STARTTLS if
220// remote supports it and optionally authenticates. If successful, a client is
221// returned on which eventually Close must be called. Otherwise an error is
222// returned and the caller is responsible for closing the connection.
224// Connecting to the correct host is outside the scope of the client. The queue
225// managing outgoing messages decides which host to deliver to, taking multiple MX
226// records with preferences, other DNS records, MTA-STS, retries and special
227// cases into account.
229// tlsMode indicates if and how TLS may/must (not) be used. tlsVerifyPKIX
230// indicates if TLS certificates must be validated against the PKIX/WebPKI
231// certificate authorities (if TLS is done). DANE-verification is done when
232// opts.DANERecords is not nil. TLS verification errors will be ignored if
233// opts.IgnoreTLSVerification is set. If TLS is done, PKIX verification is
234// always performed for tracking the results for TLS reporting, but if
235// tlsVerifyPKIX is false, the verification result does not affect the
236// connection. At the time of writing, delivery of email on the internet is done
237// with opportunistic TLS without PKIX verification by default. Recipient domains
238// can opt-in to PKIX verification by publishing an MTA-STS policy, or opt-in to
239// DANE verification by publishing DNSSEC-protected TLSA records in DNS.
240func New(ctx context.Context, log *mlog.Log, conn net.Conn, tlsMode TLSMode, tlsVerifyPKIX bool, ehloHostname, remoteHostname dns.Domain, opts Opts) (*Client, error) {
241 ensureResult := func(r *tlsrpt.Result) *tlsrpt.Result {
243 return &tlsrpt.Result{}
250 tlsVerifyPKIX: tlsVerifyPKIX,
251 ignoreTLSVerifyErrors: opts.IgnoreTLSVerifyErrors,
252 rootCAs: opts.RootCAs,
253 remoteHostname: remoteHostname,
254 daneRecords: opts.DANERecords,
255 daneMoreHostnames: opts.DANEMoreHostnames,
256 daneVerifiedRecord: opts.DANEVerifiedRecord,
258 cmds: []string{"(none)"},
259 recipientDomainResult: ensureResult(opts.RecipientDomainResult),
260 hostResult: ensureResult(opts.HostResult),
262 c.log = log.Fields(mlog.Field("smtpclient", "")).MoreFields(func() []mlog.Pair {
265 mlog.Field("delta", now.Sub(c.lastlog)),
271 if tlsMode == TLSImmediate {
272 config := c.tlsConfig()
273 tlsconn := tls.Client(conn, config)
274 // The tlsrpt tracking isn't used by caller, but won't hurt.
275 if err := tlsconn.HandshakeContext(ctx); err != nil {
276 c.tlsResultAdd(0, 1, err)
279 c.firstReadAfterHandshake = true
280 c.tlsResultAdd(1, 0, nil)
282 tlsversion, ciphersuite := mox.TLSInfo(tlsconn)
283 c.log.Debug("tls client handshake done", mlog.Field("tls", tlsversion), mlog.Field("ciphersuite", ciphersuite), mlog.Field("servername", remoteHostname))
289 // We don't wrap reads in a timeoutReader for fear of an optional TLS wrapper doing
290 // reads without the client asking for it. Such reads could result in a timeout
292 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
293 c.r = bufio.NewReader(c.tr)
294 // We use a single write timeout of 30 seconds.
296 c.tw = moxio.NewTraceWriter(c.log, "LC: ", timeoutWriter{c.conn, 30 * time.Second, c.log})
297 c.w = bufio.NewWriter(c.tw)
299 if err := c.hello(ctx, tlsMode, ehloHostname, opts.Auth); err != nil {
305// reportedError wraps an error while indicating it was already tracked for TLS
307type reportedError struct{ err error }
309func (e reportedError) Error() string {
313func (e reportedError) Unwrap() error {
317func (c *Client) tlsConfig() *tls.Config {
318 // We always manage verification ourselves: We need to report in detail about
319 // failures. And we may have to verify both PKIX and DANE, record errors for
320 // each, and possibly ignore the errors.
322 verifyConnection := func(cs tls.ConnectionState) error {
323 // Collect verification errors. If there are none at the end, TLS validation
324 // succeeded. We may find validation problems below, record them for a TLS report
325 // but continue due to policies. We track the TLS reporting result in this
326 // function, wrapping errors in a reportedError.
327 var daneErr, pkixErr error
329 // DANE verification.
330 // daneRecords can be non-nil and empty, that's intended.
331 if c.daneRecords != nil {
332 verified, record, err := dane.Verify(c.log, c.daneRecords, cs, c.remoteHostname, c.daneMoreHostnames)
333 c.log.Debugx("dane verification", err, mlog.Field("verified", verified), mlog.Field("record", record))
335 if c.daneVerifiedRecord != nil {
336 *c.daneVerifiedRecord = record
339 // Track error for reports.
340 // 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
341 fd := c.tlsrptFailureDetails(tlsrpt.ResultValidationFailure, "dane-no-match")
343 // 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.
345 // We may have encountered errors while evaluation some of the TLSA records.
346 fd.FailureReasonCode += "+errors"
348 c.hostResult.Add(0, 0, fd)
350 if c.ignoreTLSVerifyErrors {
351 // We ignore the failure and continue the connection.
352 c.log.Infox("verifying dane failed, continuing with connection", err)
353 metricTLSRequiredNoIgnored.WithLabelValues("daneverification").Inc()
355 // This connection will fail.
356 daneErr = dane.ErrNoMatch
361 // PKIX verification.
362 opts := x509.VerifyOptions{
363 DNSName: cs.ServerName,
364 Intermediates: x509.NewCertPool(),
367 for _, cert := range cs.PeerCertificates[1:] {
368 opts.Intermediates.AddCert(cert)
370 if _, err := cs.PeerCertificates[0].Verify(opts); err != nil {
371 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
372 fd := c.tlsrptFailureDetails(resultType, reasonCode)
373 c.recipientDomainResult.Add(0, 0, fd)
375 if c.tlsVerifyPKIX && !c.ignoreTLSVerifyErrors {
380 if daneErr != nil && pkixErr != nil {
381 return reportedError{errors.Join(daneErr, pkixErr)}
382 } else if daneErr != nil {
383 return reportedError{daneErr}
384 } else if pkixErr != nil {
385 return reportedError{pkixErr}
391 ServerName: c.remoteHostname.ASCII, // For SNI.
392 // todo: possibly accept older TLS versions for TLSOpportunistic? or would our private key be at risk?
394 InsecureSkipVerify: true, // VerifyConnection below is called and will do all verification.
395 VerifyConnection: verifyConnection,
399// xbotchf generates a temporary error and marks the client as botched. e.g. for
400// i/o errors or invalid protocol messages.
401func (c *Client) xbotchf(code int, secode string, lastLine, format string, args ...any) {
402 panic(c.botchf(code, secode, lastLine, format, args...))
405// botchf generates a temporary error and marks the client as botched. e.g. for
406// i/o errors or invalid protocol messages.
407func (c *Client) botchf(code int, secode string, lastLine, format string, args ...any) error {
409 return c.errorf(false, code, secode, lastLine, format, args...)
412func (c *Client) errorf(permanent bool, code int, secode, lastLine, format string, args ...any) error {
417 return Error{permanent, code, secode, cmd, lastLine, fmt.Errorf(format, args...)}
420func (c *Client) xerrorf(permanent bool, code int, secode, lastLine, format string, args ...any) {
421 panic(c.errorf(permanent, code, secode, lastLine, format, args...))
424// timeoutWriter passes each Write on to conn after setting a write deadline on conn based on
426type timeoutWriter struct {
428 timeout time.Duration
432func (w timeoutWriter) Write(buf []byte) (int, error) {
433 if err := w.conn.SetWriteDeadline(time.Now().Add(w.timeout)); err != nil {
434 w.log.Errorx("setting write deadline", err)
437 return w.conn.Write(buf)
440var bufs = moxio.NewBufpool(8, 2*1024)
442func (c *Client) readline() (string, error) {
443 // todo: could have per-operation timeouts. and rfc suggests higher minimum timeouts.
../rfc/5321:3610
444 if err := c.conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
445 c.log.Errorx("setting read deadline", err)
448 line, err := bufs.Readline(c.r)
450 // See if this is a TLS alert from remote, and one other than 0 (which notifies
451 // that the connection is being closed. If so, we register a TLS connection
452 // failure. This handles TLS alerts that happen just after a successful handshake.
453 var netErr *net.OpError
454 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 {
455 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
456 // We count -1 success to compensate for the assumed success right after the handshake.
457 c.tlsResultAddFailureDetails(-1, 1, c.tlsrptFailureDetails(resultType, reasonCode))
460 return line, c.botchf(0, "", "", "%s: %w", strings.Join(c.cmds, ","), err)
462 c.firstReadAfterHandshake = false
466func (c *Client) xtrace(level mlog.Level) func() {
472 c.tr.SetTrace(mlog.LevelTrace)
473 c.tw.SetTrace(mlog.LevelTrace)
477func (c *Client) xwritelinef(format string, args ...any) {
478 c.xbwritelinef(format, args...)
482func (c *Client) xwriteline(line string) {
487func (c *Client) xbwritelinef(format string, args ...any) {
488 c.xbwriteline(fmt.Sprintf(format, args...))
491func (c *Client) xbwriteline(line string) {
492 _, err := fmt.Fprintf(c.w, "%s\r\n", line)
494 c.xbotchf(0, "", "", "write: %w", err)
498func (c *Client) xflush() {
501 c.xbotchf(0, "", "", "writes: %w", err)
505// read response, possibly multiline, with supporting extended codes based on configuration in client.
506func (c *Client) xread() (code int, secode, lastLine string, texts []string) {
508 code, secode, lastLine, texts, err = c.read()
515func (c *Client) read() (code int, secode, lastLine string, texts []string, rerr error) {
516 return c.readecode(c.extEcodes)
519// read response, possibly multiline.
520// if ecodes, extended codes are parsed.
521func (c *Client) readecode(ecodes bool) (code int, secode, lastLine string, texts []string, rerr error) {
523 co, sec, text, line, last, err := c.read1(ecodes)
528 texts = append(texts, text)
529 if code != 0 && co != code {
531 err := c.botchf(0, "", line, "%w: multiline response with different codes, previous %d, last %d", ErrProtocol, code, co)
532 return 0, "", "", nil, err
536 if code != smtp.C334ContinueAuth {
540 // We only keep the last, so we're not creating new slices all the time.
545 metricCommands.WithLabelValues(cmd, fmt.Sprintf("%d", co), sec).Observe(float64(time.Since(c.cmdStart)) / float64(time.Second))
546 c.log.Debug("smtpclient command result", mlog.Field("cmd", cmd), mlog.Field("code", co), mlog.Field("secode", sec), mlog.Field("duration", time.Since(c.cmdStart)))
548 return co, sec, line, texts, nil
553func (c *Client) xreadecode(ecodes bool) (code int, secode, lastLine string, texts []string) {
555 code, secode, lastLine, texts, err = c.readecode(ecodes)
562// read single response line.
563// if ecodes, extended codes are parsed.
564func (c *Client) read1(ecodes bool) (code int, secode, text, line string, last bool, rerr error) {
565 line, rerr = c.readline()
570 for ; i < len(line) && line[i] >= '0' && line[i] <= '9'; i++ {
573 rerr = c.botchf(0, "", line, "%w: expected response code: %s", ErrProtocol, line)
576 v, err := strconv.ParseInt(line[:i], 10, 32)
578 rerr = c.botchf(0, "", line, "%w: bad response code (%s): %s", ErrProtocol, err, line)
584 if strings.HasPrefix(s, "-") || strings.HasPrefix(s, " ") {
591 rerr = c.botchf(0, "", line, "%w: expected space or dash after response code: %s", ErrProtocol, line)
596 secode, s = parseEcode(major, s)
599 return code, secode, s, line, last, nil
602func parseEcode(major int, s string) (secode string, remain string) {
605 take := func(need bool, a, b byte) bool {
606 if !bad && o < len(s) && s[o] >= a && s[o] <= b {
613 digit := func(need bool) bool {
614 return take(need, '0', '9')
617 return take(true, '.', '.')
631 take(false, ' ', ' ')
632 if bad || int(s[0])-int('0') != major {
638func (c *Client) recover(rerr *error) {
643 cerr, ok := x.(Error)
645 metrics.PanicInc(metrics.Smtpclient)
651func (c *Client) hello(ctx context.Context, tlsMode TLSMode, ehloHostname dns.Domain, auth []sasl.Client) (rerr error) {
652 defer c.recover(&rerr)
654 // perform EHLO handshake, falling back to HELO if server does not appear to
656 hello := func(heloOK bool) {
657 // Write EHLO and parse the supported extensions.
660 c.cmdStart = time.Now()
662 c.xwritelinef("EHLO %s", ehloHostname.ASCII)
663 code, _, lastLine, remains := c.xreadecode(false)
667 case smtp.C500BadSyntax, smtp.C501BadParamSyntax, smtp.C502CmdNotImpl, smtp.C503BadCmdSeq, smtp.C504ParamNotImpl:
669 c.xerrorf(true, code, "", lastLine, "%w: remote claims ehlo is not supported", ErrProtocol)
673 c.cmdStart = time.Now()
674 c.xwritelinef("HELO %s", ehloHostname.ASCII)
675 code, _, lastLine, _ = c.xreadecode(false)
676 if code != smtp.C250Completed {
677 c.xerrorf(code/100 == 5, code, "", lastLine, "%w: expected 250 to HELO, got %d", ErrStatus, code)
680 case smtp.C250Completed:
682 c.xerrorf(code/100 == 5, code, "", lastLine, "%w: expected 250, got %d", ErrStatus, code)
684 for _, s := range remains[1:] {
686 s = strings.ToUpper(strings.TrimSpace(s))
690 case "ENHANCEDSTATUSCODES":
695 c.extPipelining = true
697 c.extRequireTLS = true
700 if s == "SMTPUTF8" || strings.HasPrefix(s, "SMTPUTF8 ") {
702 } else if strings.HasPrefix(s, "SIZE ") {
704 if v, err := strconv.ParseInt(s[len("SIZE "):], 10, 64); err == nil {
707 } else if strings.HasPrefix(s, "AUTH ") {
708 c.extAuthMechanisms = strings.Split(s[len("AUTH "):], " ")
715 c.cmds = []string{"(greeting)"}
716 c.cmdStart = time.Now()
717 code, _, lastLine, lines := c.xreadecode(false)
718 if code != smtp.C220ServiceReady {
719 c.xerrorf(code/100 == 5, code, "", lastLine, "%w: expected 220, got %d", ErrStatus, code)
722 c.remoteHelo, _, _ = strings.Cut(lines[0], " ")
724 // Write EHLO, falling back to HELO if server doesn't appear to support it.
727 // Attempt TLS if remote understands STARTTLS and we aren't doing immediate TLS or if caller requires it.
728 if c.extStartTLS && tlsMode == TLSOpportunistic || tlsMode == TLSRequiredStartTLS {
729 c.log.Debug("starting tls client", mlog.Field("tlsmode", tlsMode), mlog.Field("servername", c.remoteHostname))
730 c.cmds[0] = "starttls"
731 c.cmdStart = time.Now()
732 c.xwritelinef("STARTTLS")
733 code, secode, lastLine, _ := c.xread()
735 if code != smtp.C220ServiceReady {
736 c.tlsResultAddFailureDetails(0, 1, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, fmt.Sprintf("smtp-starttls-reply-code-%d", code)))
737 c.xerrorf(code/100 == 5, code, secode, lastLine, "%w: STARTTLS: got %d, expected 220", ErrTLS, code)
740 // We don't want to do TLS on top of c.r because it also prints protocol traces: We
741 // don't want to log the TLS stream. So we'll do TLS on the underlying connection,
742 // but make sure any bytes already read and in the buffer are used for the TLS
745 if n := c.r.Buffered(); n > 0 {
746 conn = &moxio.PrefixConn{
747 PrefixReader: io.LimitReader(c.r, int64(n)),
752 tlsConfig := c.tlsConfig()
753 nconn := tls.Client(conn, tlsConfig)
756 nctx, cancel := context.WithTimeout(ctx, time.Minute)
758 err := nconn.HandshakeContext(nctx)
760 // For each STARTTLS failure, we track a failed TLS session. For deliveries with
761 // multiple MX targets, we may add multiple failures, and delivery may succeed with
763 c.tlsResultAdd(0, 1, err)
764 c.xerrorf(false, 0, "", "", "%w: STARTTLS TLS handshake: %s", ErrTLS, err)
766 c.firstReadAfterHandshake = true
768 c.tr = moxio.NewTraceReader(c.log, "RS: ", c.conn)
769 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.
770 c.r = bufio.NewReader(c.tr)
771 c.w = bufio.NewWriter(c.tw)
773 tlsversion, ciphersuite := mox.TLSInfo(nconn)
774 c.log.Debug("starttls client handshake done",
775 mlog.Field("tlsmode", tlsMode),
776 mlog.Field("verifypkix", c.tlsVerifyPKIX),
777 mlog.Field("verifydane", c.daneRecords != nil),
778 mlog.Field("ignoretlsverifyerrors", c.ignoreTLSVerifyErrors),
779 mlog.Field("tls", tlsversion),
780 mlog.Field("ciphersuite", ciphersuite),
781 mlog.Field("servername", c.remoteHostname),
782 mlog.Field("danerecord", c.daneVerifiedRecord))
785 c.tlsResultAdd(1, 0, nil)
788 } else if tlsMode == TLSOpportunistic {
790 c.tlsResultAddFailureDetails(0, 0, c.tlsrptFailureDetails(tlsrpt.ResultSTARTTLSNotSupported, ""))
799func addrIP(addr net.Addr) string {
800 if t, ok := addr.(*net.TCPAddr); ok {
803 host, _, _ := net.SplitHostPort(addr.String())
804 ip := net.ParseIP(host)
806 return "" // For pipe during tests.
811// tlsrptFailureDetails returns FailureDetails with connection details (such as
812// IP addresses) for inclusion in a TLS report.
813func (c *Client) tlsrptFailureDetails(resultType tlsrpt.ResultType, reasonCode string) tlsrpt.FailureDetails {
814 return tlsrpt.FailureDetails{
815 ResultType: resultType,
816 SendingMTAIP: addrIP(c.origConn.LocalAddr()),
817 ReceivingMXHostname: c.remoteHostname.ASCII,
818 ReceivingMXHelo: c.remoteHelo,
819 ReceivingIP: addrIP(c.origConn.RemoteAddr()),
820 FailedSessionCount: 1,
821 FailureReasonCode: reasonCode,
825// tlsResultAdd adds TLS success/failure to all results.
826func (c *Client) tlsResultAdd(success, failure int64, err error) {
827 // Only track failure if not already done so in tls.Config.VerifyConnection.
828 var fds []tlsrpt.FailureDetails
829 var repErr reportedError
830 if err != nil && !errors.As(err, &repErr) {
831 resultType, reasonCode := tlsrpt.TLSFailureDetails(err)
832 fd := c.tlsrptFailureDetails(resultType, reasonCode)
833 fds = []tlsrpt.FailureDetails{fd}
835 c.tlsResultAddFailureDetails(success, failure, fds...)
838func (c *Client) tlsResultAddFailureDetails(success, failure int64, fds ...tlsrpt.FailureDetails) {
839 c.recipientDomainResult.Add(success, failure, fds...)
840 c.hostResult.Add(success, failure, fds...)
844func (c *Client) auth(auth []sasl.Client) (rerr error) {
845 defer c.recover(&rerr)
848 c.cmdStart = time.Now()
852 var cleartextCreds bool
853 for _, x := range auth {
854 name, cleartextCreds = x.Info()
855 for _, s := range c.extAuthMechanisms {
863 c.xerrorf(true, 0, "", "", "no matching authentication mechanisms, server supports %s", strings.Join(c.extAuthMechanisms, ", "))
866 abort := func() (int, string, string) {
871 code, secode, lastline, _ := c.xread()
872 if code != smtp.C501BadParamSyntax {
875 return code, secode, lastline
878 toserver, last, err := a.Next(nil)
880 c.xerrorf(false, 0, "", "", "initial step in auth mechanism %s: %w", name, err)
883 defer c.xtrace(mlog.LevelTraceauth)()
886 c.xwriteline("AUTH " + name)
887 } else if len(toserver) == 0 {
890 c.xwriteline("AUTH " + name + " " + base64.StdEncoding.EncodeToString(toserver))
893 if cleartextCreds && last {
894 c.xtrace(mlog.LevelTrace) // Restore.
897 code, secode, lastLine, texts := c.xreadecode(last)
898 if code == smtp.C235AuthSuccess {
900 c.xerrorf(false, code, secode, lastLine, "server completed authentication earlier than client expected")
903 } else if code == smtp.C334ContinueAuth {
905 c.xerrorf(false, code, secode, lastLine, "server requested unexpected continuation of authentication")
909 c.xerrorf(false, code, secode, lastLine, "server responded with multiline contination")
911 fromserver, err := base64.StdEncoding.DecodeString(texts[0])
914 c.xerrorf(false, code, secode, lastLine, "malformed base64 data in authentication continuation response")
916 toserver, last, err = a.Next(fromserver)
918 // For failing SCRAM, the client stops due to message about invalid proof. The
919 // server still sends an authentication result (it probably should send 501
921 xcode, xsecode, lastline := abort()
922 c.xerrorf(false, xcode, xsecode, lastline, "client aborted authentication: %w", err)
924 c.xwriteline(base64.StdEncoding.EncodeToString(toserver))
926 c.xerrorf(code/100 == 5, code, secode, lastLine, "unexpected response during authentication, expected 334 continue or 235 auth success")
931// Supports8BITMIME returns whether the SMTP server supports the 8BITMIME
932// extension, needed for sending data with non-ASCII bytes.
933func (c *Client) Supports8BITMIME() bool {
937// SupportsSMTPUTF8 returns whether the SMTP server supports the SMTPUTF8
938// extension, needed for sending messages with UTF-8 in headers or in an (SMTP)
940func (c *Client) SupportsSMTPUTF8() bool {
944// SupportsStartTLS returns whether the SMTP server supports the STARTTLS
946func (c *Client) SupportsStartTLS() bool {
950// SupportsRequireTLS returns whether the SMTP server supports the REQUIRETLS
951// extension. The REQUIRETLS extension is only announced after enabling
953func (c *Client) SupportsRequireTLS() bool {
954 return c.extRequireTLS
957// TLSEnabled returns whether TLS is enabled for this connection.
958func (c *Client) TLSEnabled() bool {
962// Deliver attempts to deliver a message to a mail server.
964// mailFrom must be an email address, or empty in case of a DSN. rcptTo must be
967// If the message contains bytes with the high bit set, req8bitmime must be true. If
968// set, the remote server must support the 8BITMIME extension or delivery will
971// If the message is internationalized, e.g. when headers contain non-ASCII
972// character, or when UTF-8 is used in a localpart, reqSMTPUTF8 must be true. If set,
973// the remote server must support the SMTPUTF8 extension or delivery will fail.
975// If requireTLS is true, the remote server must support the REQUIRETLS
976// extension, or delivery will fail.
978// Deliver uses the following SMTP extensions if the remote server supports them:
979// 8BITMIME, SMTPUTF8, SIZE, PIPELINING, ENHANCEDSTATUSCODES, STARTTLS.
981// Returned errors can be of type Error, one of the Err-variables in this package
982// or other underlying errors, e.g. for i/o. Use errors.Is to check.
983func (c *Client) Deliver(ctx context.Context, mailFrom string, rcptTo string, msgSize int64, msg io.Reader, req8bitmime, reqSMTPUTF8, requireTLS bool) (rerr error) {
984 defer c.recover(&rerr)
986 if c.origConn == nil {
988 } else if c.botched {
990 } else if c.needRset {
991 if err := c.Reset(); err != nil {
996 if !c.ext8bitmime && req8bitmime {
997 // Temporary error, e.g. OpenBSD spamd does not announce 8bitmime support, but once
998 // you get through, the mail server behind it probably does. Just needs a few
1000 c.xerrorf(false, 0, "", "", "%w", Err8bitmimeUnsupported)
1002 if !c.extSMTPUTF8 && reqSMTPUTF8 {
1004 c.xerrorf(false, 0, "", "", "%w", ErrSMTPUTF8Unsupported)
1006 if !c.extRequireTLS && requireTLS {
1007 c.xerrorf(false, 0, "", "", "%w", ErrRequireTLSUnsupported)
1010 if c.extSize && msgSize > c.maxSize {
1011 c.xerrorf(true, 0, "", "", "%w: message is %d bytes, remote has a %d bytes maximum size", ErrSize, msgSize, c.maxSize)
1014 var mailSize, bodyType string
1016 mailSize = fmt.Sprintf(" SIZE=%d", msgSize)
1020 bodyType = " BODY=8BITMIME"
1022 bodyType = " BODY=7BIT"
1025 var smtputf8Arg string
1028 smtputf8Arg = " SMTPUTF8"
1030 var requiretlsArg string
1033 requiretlsArg = " REQUIRETLS"
1040 lineMailFrom := fmt.Sprintf("MAIL FROM:<%s>%s%s%s%s", mailFrom, mailSize, bodyType, smtputf8Arg, requiretlsArg)
1041 lineRcptTo := fmt.Sprintf("RCPT TO:<%s>", rcptTo)
1043 // We are going into a transaction. We'll clear this when done.
1046 if c.extPipelining {
1047 c.cmds = []string{"mailfrom", "rcptto", "data"}
1048 c.cmdStart = time.Now()
1049 // todo future: write in a goroutine to prevent potential deadlock if remote does not consume our writes before expecting us to read. could potentially happen with greylisting and a small tcp send window?
1050 c.xbwriteline(lineMailFrom)
1051 c.xbwriteline(lineRcptTo)
1052 c.xbwriteline("DATA")
1055 // We read the response to RCPT TO and DATA without panic on read error. Servers
1056 // may be aborting the connection after a failed MAIL FROM, e.g. outlook when it
1057 // has blocklisted your IP. We don't want the read for the response to RCPT TO to
1058 // cause a read error as it would result in an unhelpful error message and a
1059 // temporary instead of permanent error code.
1061 mfcode, mfsecode, mflastline, _ := c.xread()
1062 rtcode, rtsecode, rtlastline, _, rterr := c.read()
1063 datacode, datasecode, datalastline, _, dataerr := c.read()
1065 if mfcode != smtp.C250Completed {
1066 c.xerrorf(mfcode/100 == 5, mfcode, mfsecode, mflastline, "%w: got %d, expected 2xx", ErrStatus, mfcode)
1071 if rtcode != smtp.C250Completed {
1072 c.xerrorf(rtcode/100 == 5, rtcode, rtsecode, rtlastline, "%w: got %d, expected 2xx", ErrStatus, rtcode)
1077 if datacode != smtp.C354Continue {
1078 c.xerrorf(datacode/100 == 5, datacode, datasecode, datalastline, "%w: got %d, expected 354", ErrStatus, datacode)
1081 c.cmds[0] = "mailfrom"
1082 c.cmdStart = time.Now()
1083 c.xwriteline(lineMailFrom)
1084 code, secode, lastline, _ := c.xread()
1085 if code != smtp.C250Completed {
1086 c.xerrorf(code/100 == 5, code, secode, lastline, "%w: got %d, expected 2xx", ErrStatus, code)
1089 c.cmds[0] = "rcptto"
1090 c.cmdStart = time.Now()
1091 c.xwriteline(lineRcptTo)
1092 code, secode, lastline, _ = c.xread()
1093 if code != smtp.C250Completed {
1094 c.xerrorf(code/100 == 5, code, secode, lastline, "%w: got %d, expected 2xx", ErrStatus, code)
1098 c.cmdStart = time.Now()
1099 c.xwriteline("DATA")
1100 code, secode, lastline, _ = c.xread()
1101 if code != smtp.C354Continue {
1102 c.xerrorf(code/100 == 5, code, secode, lastline, "%w: got %d, expected 354", ErrStatus, code)
1106 // For a DATA write, the suggested timeout is 3 minutes, we use 30 seconds for all
1108 defer c.xtrace(mlog.LevelTracedata)()
1109 err := smtp.DataWrite(c.w, msg)
1111 c.xbotchf(0, "", "", "writing message as smtp data: %w", err)
1114 c.xtrace(mlog.LevelTrace) // Restore.
1115 code, secode, lastline, _ := c.xread()
1116 if code != smtp.C250Completed {
1117 c.xerrorf(code/100 == 5, code, secode, lastline, "%w: got %d, expected 2xx", ErrStatus, code)
1124// Reset sends an SMTP RSET command to reset the message transaction state. Deliver
1125// automatically sends it if needed.
1126func (c *Client) Reset() (rerr error) {
1127 if c.origConn == nil {
1129 } else if c.botched {
1133 defer c.recover(&rerr)
1137 c.cmdStart = time.Now()
1138 c.xwriteline("RSET")
1139 code, secode, lastline, _ := c.xread()
1140 if code != smtp.C250Completed {
1141 c.xerrorf(code/100 == 5, code, secode, lastline, "%w: got %d, expected 2xx", ErrStatus, code)
1147// Botched returns whether this connection is botched, e.g. a protocol error
1148// occurred and the connection is in unknown state, and cannot be used for message
1150func (c *Client) Botched() bool {
1151 return c.botched || c.origConn == nil
1154// Close cleans up the client, closing the underlying connection.
1156// If the connection is in initialized and not botched, a QUIT command is sent and
1157// the response read with a short timeout before closing the underlying connection.
1159// Close returns any error encountered during QUIT and closing.
1160func (c *Client) Close() (rerr error) {
1161 if c.origConn == nil {
1165 defer c.recover(&rerr)
1170 c.cmdStart = time.Now()
1171 c.xwriteline("QUIT")
1172 if err := c.conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
1173 c.log.Infox("setting read deadline for reading quit response", err)
1174 } else if _, err := bufs.Readline(c.r); err != nil {
1175 rerr = fmt.Errorf("reading response to quit command: %v", err)
1176 c.log.Debugx("reading quit response", err)
1180 err := c.origConn.Close()
1181 if c.conn != c.origConn {
1182 // This is the TLS connection. Close will attempt to write a close notification.
1183 // But it will fail quickly because the underlying socket was closed.
1194// Conn returns the connection with initialized SMTP session. Once the caller uses
1195// this connection it is in control, and responsible for closing the connection,
1196// and other functions on the client must not be called anymore.
1197func (c *Client) Conn() (net.Conn, error) {
1198 if err := c.conn.SetDeadline(time.Time{}); err != nil {
1199 return nil, fmt.Errorf("clearing io deadlines: %w", err)