Documentation
¶
Overview ¶
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
It also implements the following extensions:
- 8BITMIME (RFC 1652)
- ENHANCEDSTATUSCODES (RFC 2034)
- AUTH (RFC 2554)
- DELIVERBY (RFC 2852)
- CHUNKING (RFC 3030)
- BINARYMIME (RFC 3030)
- STARTTLS (RFC 3207)
- DSN (RFC 3461, RFC 6533)
- SMTPUTF8 (RFC 6531)
- MT-PRIORITY (RFC 6710)
- RRVS (RFC 7293)
- REQUIRETLS (RFC 8689)
LMTP (RFC 2033) is also supported.
Additional extensions may be handled by other packages.
Index ¶
- Variables
- func CloseConnection(err error) error
- func SendMail(addr string, a sasl.Client, from string, to []string, r io.Reader) error
- func SendMailTLS(addr string, a sasl.Client, from string, to []string, r io.Reader) error
- type AuthSession
- type Backend
- type BackendFunc
- type BodyType
- type Client
- func Dial(addr string) (*Client, error)
- func DialStartTLS(addr string, tlsConfig *tls.Config) (*Client, error)
- func DialTLS(addr string, tlsConfig *tls.Config) (*Client, error)
- func NewClient(conn net.Conn) *Client
- func NewClientLMTP(conn net.Conn) *Client
- func NewClientStartTLS(conn net.Conn, tlsConfig *tls.Config) (*Client, error)
- func (c *Client) Auth(a sasl.Client) error
- func (c *Client) CheckConn(timeout time.Duration) error
- func (c *Client) Close() error
- func (c *Client) Data() (*DataCommand, error)
- func (c *Client) Extension(ext string) (bool, string)
- func (c *Client) Hello(localName string) error
- func (c *Client) Mail(from string, opts *MailOptions) error
- func (c *Client) MaxMessageSize() (size int, ok bool)
- func (c *Client) Noop() error
- func (c *Client) Pipeline() (*Pipeliner, error)
- func (c *Client) Quit() error
- func (c *Client) Rcpt(to string, opts *RcptOptions) error
- func (c *Client) Reset() error
- func (c *Client) SendMail(from string, to []string, r io.Reader) error
- func (c *Client) SupportsAuth(mech string) bool
- func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
- func (c *Client) Verify(addr string) error
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) Conn() net.Conn
- func (c *Conn) Context() context.Context
- func (c *Conn) Hostname() string
- func (c *Conn) Reject()
- func (c *Conn) Server() *Server
- func (c *Conn) Session() Session
- func (c *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool)
- func (c *Conn) XClient() *XClientAttrs
- type ConnState
- type DSNAddressType
- type DSNNotify
- type DSNReturn
- type DataCommand
- type DataResponse
- type DeliverByMode
- type DeliverByOptions
- type EnhancedCode
- type FeatureBackend
- type LMTPDataError
- type LMTPSession
- type Logger
- type MailOptions
- type Pipeliner
- type PriorityProfile
- type RcptOptions
- type SMTPError
- type Server
- type Session
- type StatusCollector
- type XClientAttrs
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrAuthFailed = &SMTPError{ Code: 535, EnhancedCode: EnhancedCode{5, 7, 8}, Message: "Authentication failed", } ErrAuthRequired = &SMTPError{ Code: 502, EnhancedCode: EnhancedCode{5, 7, 0}, Message: "Please authenticate first", } ErrAuthUnsupported = &SMTPError{ Code: 502, EnhancedCode: EnhancedCode{5, 7, 0}, Message: "Authentication not supported", } ErrAuthUnknownMechanism = &SMTPError{ Code: 504, EnhancedCode: EnhancedCode{5, 7, 4}, Message: "Unsupported authentication mechanism", } )
var EnhancedCodeNotSet = EnhancedCode{0, 0, 0}
EnhancedCodeNotSet is a nil value of EnhancedCode field in SMTPError, used to indicate that backend failed to provide enhanced status code. X.0.0 will be used (X is derived from error code).
var ErrDataReset = errors.New("smtp: message transmission aborted")
ErrDataReset is returned by Reader pased to Data function if client does not send another BDAT command and instead closes connection or issues RSET command.
var ErrDataTooLarge = &SMTPError{ Code: 552, EnhancedCode: EnhancedCode{5, 3, 4}, Message: "Maximum message size exceeded", }
var ErrServerClosed = errors.New("smtp: server already closed")
var ErrTooLongLine = errors.New("smtp: too long a line in input stream")
var NoEnhancedCode = EnhancedCode{-1, -1, -1}
NoEnhancedCode is used to indicate that enhanced error code should not be included in response.
Note that RFC 2034 requires an enhanced code to be included in all 2xx, 4xx and 5xx responses. This constant is exported for use by extensions, you should probably use EnhancedCodeNotSet instead.
Functions ¶
func CloseConnection ¶ added in v0.28.0
CloseConnection wraps err so that a Backend or Session method (NewSession, Mail, Rcpt, Data, or an AUTH step) can ask the server to send the status line for err and then immediately close the connection. It is intended for policy and abuse handling, where the peer should be cut off rather than allowed to continue the session.
The wrapped err determines the status line exactly as if it had been returned directly: wrap an *SMTPError (see Errorf) to choose the code and message, for example
return smtp.CloseConnection(smtp.Errorf(554, smtp.EnhancedCode{5, 7, 1}, "too many bad recipients"))
A 2xx *SMTPError sends that success line and then closes (a graceful goodbye); any other error sends its rejection and then closes. Wrapping a nil error is a no-op and returns nil, so it never terminates the connection.
Connection termination is honored for the SMTP commands MAIL, RCPT, DATA and BDAT, for NewSession, and for AUTH. It is not applied to per-recipient LMTP data responses.
func SendMail ¶
SendMail connects to the server at addr, switches to TLS, authenticates with the optional SASL client, and then sends an email from address from, to addresses to, with message r. The addr must include a port, as in "mail.example.com:smtp".
The addresses in the to parameter are the SMTP RCPT addresses.
The r parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of r should be CRLF terminated. The r headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the r headers.
SendMail is intended to be used for very simple use-cases. If you want to customize SendMail's behavior, use a Client instead.
The SendMail function and the go-smtp package are low-level mechanisms and provide no support for DKIM signing (see go-msgauth), MIME attachments (see the mime/multipart package or the go-message package), or other mail functionality.
Example ¶
package main
import (
"log"
"strings"
"github.com/emersion/go-sasl"
"github.com/rest-mail/go-smtp"
)
func main() {
// Set up authentication information.
auth := sasl.NewPlainClient("", "user@example.com", "password")
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
to := []string{"recipient@example.net"}
msg := strings.NewReader("To: recipient@example.net\r\n" +
"Subject: discount Gophers!\r\n" +
"\r\n" +
"This is the email body.\r\n")
err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
if err != nil {
log.Fatal(err)
}
}
Output:
Example (PlainAuth) ¶
package main
import (
"log"
"strings"
"github.com/emersion/go-sasl"
"github.com/rest-mail/go-smtp"
)
// variables to make ExamplePlainAuth compile, without adding
// unnecessary noise there.
var (
from = "gopher@example.net"
msg = strings.NewReader("dummy message")
recipients = []string{"foo@example.com"}
)
func main() {
// hostname is used by PlainAuth to validate the TLS certificate.
hostname := "mail.example.com"
auth := sasl.NewPlainClient("", "user@example.com", "password")
err := smtp.SendMail(hostname+":25", auth, from, recipients, msg)
if err != nil {
log.Fatal(err)
}
}
Output:
Types ¶
type AuthSession ¶
type AuthSession interface {
Session
AuthMechanisms() []string
Auth(mech string) (sasl.Server, error)
}
AuthSession is an add-on interface for Session. It provides support for the AUTH extension.
type BackendFunc ¶
BackendFunc is an adapter to allow the use of an ordinary function as a Backend.
func (BackendFunc) NewSession ¶
func (f BackendFunc) NewSession(c *Conn) (Session, error)
NewSession calls f(c).
type Client ¶
type Client struct {
// Time to wait for command responses (this includes 3xx reply to DATA).
CommandTimeout time.Duration
// Time to wait for responses after final dot.
SubmissionTimeout time.Duration
// Logger for all network activity.
DebugWriter io.Writer
// contains filtered or unexported fields
}
A Client represents a client connection to an SMTP server.
func Dial ¶
Dial returns a new Client connected to an SMTP server at addr. The addr must include a port, as in "mail.example.com:smtp".
This function returns a plaintext connection. To enable TLS, use DialStartTLS.
Example ¶
package main
import (
"fmt"
"log"
"github.com/rest-mail/go-smtp"
)
func main() {
// Connect to the remote SMTP server.
c, err := smtp.Dial("mail.example.com:25")
if err != nil {
log.Fatal(err)
}
// Set the sender and recipient first
if err := c.Mail("sender@example.org", nil); err != nil {
log.Fatal(err)
}
if err := c.Rcpt("recipient@example.net", nil); err != nil {
log.Fatal(err)
}
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
_, err = fmt.Fprintf(wc, "This is the email body")
if err != nil {
log.Fatal(err)
}
err = wc.Close()
if err != nil {
log.Fatal(err)
}
// Send the QUIT command and close the connection.
err = c.Quit()
if err != nil {
log.Fatal(err)
}
}
Output:
func DialStartTLS ¶
DialStartTLS returns a new Client connected to an SMTP server via STARTTLS at addr. The addr must include a port, as in "mail.example.com:smtp".
A nil tlsConfig is equivalent to a zero tls.Config.
func DialTLS ¶
DialTLS returns a new Client connected to an SMTP server via TLS at addr. The addr must include a port, as in "mail.example.com:smtps".
A nil tlsConfig is equivalent to a zero tls.Config.
func NewClient ¶
NewClient returns a new Client using an existing connection and host as a server name to be used when authenticating.
func NewClientLMTP ¶
NewClientLMTP returns a new LMTP Client (as defined in RFC 2033) using an existing connection and host as a server name to be used when authenticating.
func NewClientStartTLS ¶
NewClientStartTLS creates a new Client and performs a STARTTLS command.
func (*Client) Auth ¶
Auth authenticates a client using the provided authentication mechanism. Only servers that advertise the AUTH extension support this function.
If server returns an error, it will be of type *SMTPError.
func (*Client) CheckConn ¶ added in v0.28.0
CheckConn reports whether a pooled connection that has been sitting idle is still usable, detecting the common case where the server closed it while it was idle. It performs a read-ahead only: it never sends a command, so it adds no round-trip and cannot disturb an in-flight transaction.
It must be called only when the client is idle — no command is awaiting a response and no DATA transfer is in progress. On such a connection the server sends nothing until the next command, so CheckConn interprets a read as follows:
- the read blocks for up to timeout and returns no data: the connection appears healthy and CheckConn returns nil;
- the read reports the peer has closed the connection (io.EOF or another error): CheckConn returns that error;
- data is already waiting, or arrives: the server sent something unsolicited, so the connection is not cleanly idle and CheckConn returns a non-nil error.
A non-nil result means the connection should be closed and not reused. Because the check is a best-effort probe, a healthy result is not a guarantee the next command will succeed; a small positive timeout (e.g. a few tens of milliseconds) gives an in-flight FIN time to arrive, while timeout <= 0 makes it a pure non-blocking poll.
CheckConn is safe on a STARTTLS/implicit-TLS connection: the probe reads through the *tls.Conn, which preserves any partially received TLS record internally when the read times out, so a subsequent command reads the stream intact. It never reads the raw socket beneath the TLS layer.
func (*Client) Data ¶
func (c *Client) Data() (*DataCommand, error)
Data issues a DATA command to the server and returns a writer that can be used to write the mail headers and body. The caller should close the writer before calling any more methods on c. A call to Data must be preceded by one or more calls to Rcpt.
func (*Client) Extension ¶
Extension reports whether an extension is support by the server. The extension name is case-insensitive. If the extension is supported, Extension also returns a string that contains any parameters the server specifies for the extension.
func (*Client) Hello ¶
Hello sends a HELO or EHLO to the server as the given host name. Calling this method is only necessary if the client needs control over the host name used. The client will introduce itself as "localhost" automatically otherwise. If Hello is called, it must be called before any of the other methods.
If server returns an error, it will be of type *SMTPError.
func (*Client) Mail ¶
func (c *Client) Mail(from string, opts *MailOptions) error
Mail issues a MAIL command to the server using the provided email address. If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME parameter. This initiates a mail transaction and is followed by one or more Rcpt calls.
If opts is not nil, MAIL arguments provided in the structure will be added to the command. Handling of unsupported options depends on the extension.
If server returns an error, it will be of type *SMTPError.
func (*Client) MaxMessageSize ¶
MaxMessageSize returns the maximum message size accepted by the server. 0 means unlimited.
If the server doesn't convey this information, ok = false is returned.
func (*Client) Noop ¶
Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.
func (*Client) Pipeline ¶ added in v0.28.0
Pipeline begins a pipelined command group (see Pipeliner).
It returns an error if the server has not advertised the PIPELINING extension (RFC 2920): pipelining to a server that has not opted in risks the server processing a command, replying, and closing the connection before it reads the rest of the group. Callers should fall back to the one-at-a-time Mail and Rcpt methods in that case.
func (*Client) Quit ¶
Quit sends the QUIT command and closes the connection to the server.
If Quit fails the connection is not closed, Close should be used in this case.
func (*Client) Rcpt ¶
func (c *Client) Rcpt(to string, opts *RcptOptions) error
Rcpt issues a RCPT command to the server using the provided email address. A call to Rcpt must be preceded by a call to Mail and may be followed by a Data call or another Rcpt call.
If opts is not nil, RCPT arguments provided in the structure will be added to the command. Handling of unsupported options depends on the extension.
If server returns an error, it will be of type *SMTPError.
func (*Client) Reset ¶
Reset sends the RSET command to the server, aborting the current mail transaction.
func (*Client) SendMail ¶
SendMail will use an existing connection to send an email from address from, to addresses to, with message r.
This function does not start TLS, nor does it perform authentication. Use DialStartTLS and Auth before-hand if desirable.
The addresses in the to parameter are the SMTP RCPT addresses.
The r parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of r should be CRLF terminated. The r headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the r headers.
func (*Client) SupportsAuth ¶
SupportsAuth checks whether an authentication mechanism is supported.
func (*Client) TLSConnectionState ¶
func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
TLSConnectionState returns the client's TLS connection state. The return values are their zero values if STARTTLS did not succeed.
func (*Client) Verify ¶
Verify checks the validity of an email address on the server. If Verify returns nil, the address is valid. A non-nil return does not necessarily indicate an invalid address. Many servers will not verify addresses for security reasons.
If server returns an error, it will be of type *SMTPError.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
func (*Conn) Context ¶ added in v0.27.0
Context returns the connection's context. It is cancelled when the connection is closed or the server is shut down, so a backend can observe those events (for example to cancel in-flight work). It is never nil.
func (*Conn) TLSConnectionState ¶
func (c *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool)
TLSConnectionState returns the connection's TLS connection state. Zero values are returned if the connection doesn't use TLS.
func (*Conn) XClient ¶ added in v0.27.0
func (c *Conn) XClient() *XClientAttrs
XClient returns the client identity a trusted proxy asserted via XCLIENT, or nil if none was asserted on this connection. See Server.EnableXCLIENT.
type ConnState ¶ added in v0.27.0
type ConnState int
ConnState represents the lifecycle state of a client connection, as reported to Server.ConnState.
type DSNAddressType ¶
type DSNAddressType string
const ( DSNAddressTypeRFC822 DSNAddressType = "RFC822" DSNAddressTypeUTF8 DSNAddressType = "UTF-8" )
type DataCommand ¶
type DataCommand struct {
// contains filtered or unexported fields
}
DataCommand is a pending DATA command. DataCommand is an io.WriteCloser. See Client.Data.
func (*DataCommand) CloseWithLMTPResponse ¶
func (cmd *DataCommand) CloseWithLMTPResponse() (map[string]*DataResponse, error)
CloseWithLMTPResponse is equivalent to Close, but also returns per-recipient server responses. It can only be called when the LMTP protocol is used.
If server returns an error, it will be of type LMTPDataError.
func (*DataCommand) CloseWithResponse ¶
func (cmd *DataCommand) CloseWithResponse() (*DataResponse, error)
CloseWithResponse is equivalent to Close, but also returns the server response. It cannot be called when the LMTP protocol is used.
If server returns an error, it will be of type *SMTPError.
type DataResponse ¶
type DataResponse struct {
// StatusText is the status text returned by the server. It may contain
// tracking information.
StatusText string
}
DataResponse is the response returned by a DATA command. See DataCommand.CloseWithResponse.
type DeliverByMode ¶
type DeliverByMode string
const ( DeliverByNotify DeliverByMode = "N" DeliverByReturn DeliverByMode = "R" )
type DeliverByOptions ¶
type DeliverByOptions struct {
Time time.Duration
Mode DeliverByMode
Trace bool
}
type EnhancedCode ¶
type EnhancedCode [3]int
type FeatureBackend ¶ added in v0.27.0
FeatureBackend is an optional interface a Backend may implement to advertise additional ESMTP capabilities in the EHLO response, computed per connection.
The returned strings are appended after the server's built-in capabilities and Server.ExtraCaps; each entry is one capability line, advertised verbatim (e.g. "X-EXAMPLE" or "SIZE 1024"). It is the backend's responsibility to handle any command an advertised extension defines. Returning nil advertises nothing extra.
type LMTPDataError ¶
LMTPDataError is a collection of errors returned by an LMTP server for a DATA command. It holds per-recipient errors.
func (LMTPDataError) Unwrap ¶
func (lmtpErr LMTPDataError) Unwrap() []error
Unwrap returns all per-recipient errors returned by the server.
type LMTPSession ¶
type LMTPSession interface {
Session
// LMTPData is the LMTP-specific version of Data method.
// It can be optionally implemented by the backend to provide
// per-recipient status information when it is used over LMTP
// protocol.
//
// LMTPData implementation sets status information using passed
// StatusCollector by calling SetStatus once per each AddRcpt
// call, even if AddRcpt was called multiple times with
// the same argument. SetStatus must not be called after
// LMTPData returns.
//
// Return value of LMTPData itself is used as a status for
// recipients that got no status set before using StatusCollector.
LMTPData(r io.Reader, status StatusCollector) error
}
LMTPSession is an add-on interface for Session. It can be implemented by LMTP servers to provide extra functionality.
type Logger ¶
type Logger interface {
Printf(format string, v ...interface{})
Println(v ...interface{})
}
Logger interface is used by Server to report unexpected internal errors.
type MailOptions ¶
type MailOptions struct {
// Value of BODY= argument, 7BIT, 8BITMIME or BINARYMIME.
Body BodyType
// Size of the body. Can be 0 if not specified by client.
Size int64
// TLS is required for the message transmission.
//
// The message should be rejected if it can't be transmitted
// with TLS.
RequireTLS bool
// The message envelope or message header contains UTF-8-encoded strings.
// This flag is set by SMTPUTF8-aware (RFC 6531) client.
UTF8 bool
// Value of RET= argument, FULL or HDRS.
Return DSNReturn
// Envelope identifier set by the client.
EnvelopeID string
// The authorization identity asserted by the message sender in decoded
// form with angle brackets stripped.
//
// nil value indicates missing AUTH, non-nil empty string indicates
// AUTH=<>.
//
// Defined in RFC 4954.
Auth *string
}
MailOptions contains parameters for the MAIL command.
type Pipeliner ¶ added in v0.28.0
type Pipeliner struct {
// contains filtered or unexported fields
}
Pipeliner sends a group of RSET, MAIL FROM and RCPT TO commands using the PIPELINING extension (RFC 2920): the commands are written back-to-back without the client waiting for a response between them, saving a network round-trip per command for high-throughput senders.
Those three are the only commands RFC 2920 permits inside a pipelined group. EHLO, DATA, VRFY and QUIT must end a group, so they are issued afterwards with the Client's normal (synchronous) methods.
Obtain a Pipeliner with Client.Pipeline. Queue commands with Reset, Mail and Rcpt — each writes its command immediately but does not read the response. Call Wait to read all queued responses, in order, ending the group; the Client is then back in synchronous mode, so a message body is sent with the usual Client.Data:
p, err := c.Pipeline()
if err != nil {
// server does not support PIPELINING; fall back to c.Mail/c.Rcpt
}
p.Mail(from, nil)
for _, rcpt := range rcpts {
p.Rcpt(rcpt, nil)
}
errs := p.Wait() // errs[0] is MAIL's result, errs[1:] the RCPTs' in order
w, err := c.Data()
// ... write the message, w.Close() ...
A Pipeliner must not be used concurrently, and no other method of the underlying Client may be called between the first queued command and Wait, or responses will be read out of order.
func (*Pipeliner) Mail ¶ added in v0.28.0
func (p *Pipeliner) Mail(from string, opts *MailOptions) error
Mail queues a MAIL FROM command. Option handling matches Client.Mail. The error is non-nil only if the command could not be composed or sent (e.g. local validation failed or the write failed); the server's response is read later by Wait.
func (*Pipeliner) Rcpt ¶ added in v0.28.0
func (p *Pipeliner) Rcpt(to string, opts *RcptOptions) error
Rcpt queues a RCPT TO command. Option handling matches Client.Rcpt. The error is non-nil only if the command could not be composed or sent; the server's response is read later by Wait, and on success the recipient is added to the set used by a subsequent Data (or LMTP) call.
func (*Pipeliner) Reset ¶ added in v0.28.0
Reset queues an RSET command, aborting the current mail transaction. Unlike Client.Reset it does not reset the greeting state (a pipelined group stays within one session); when Wait reads a successful response, the pending recipient list is cleared.
func (*Pipeliner) Wait ¶ added in v0.28.0
Wait reads the server responses to all queued commands, in order, and returns one error per command index-aligned with the order the commands were queued (nil means that command succeeded; a rejection is an *SMTPError). It ends the pipelined group: the Client returns to synchronous operation and the Pipeliner is drained, so it can be reused for another group.
Wait applies the state changes of the successful commands as it reads them: a successful RSET clears the recipient set, and a successful RCPT adds its recipient to the set used by the subsequent Data (or LMTP) call.
Wait returns nil when no commands are queued.
type PriorityProfile ¶
type PriorityProfile string
const ( PriorityUnspecified PriorityProfile = "" PriorityMIXER PriorityProfile = "MIXER" PrioritySTANAG4406 PriorityProfile = "STANAG4406" PriorityNSEP PriorityProfile = "NSEP" )
type RcptOptions ¶
type RcptOptions struct {
// Value of NOTIFY= argument, NEVER or a combination of either of
// DELAY, FAILURE, SUCCESS.
Notify []DSNNotify
// Original recipient set by client.
OriginalRecipientType DSNAddressType
OriginalRecipient string
// Time value of the RRVS= argument
// or the zero time if unset.
RequireRecipientValidSince time.Time
// Value of BY= argument or nil if unset.
DeliverBy *DeliverByOptions
// Value of MT-PRIORITY= or nil if unset.
MTPriority *int
}
RcptOptions contains parameters for the RCPT command.
type SMTPError ¶
type SMTPError struct {
Code int
EnhancedCode EnhancedCode
Message string
}
SMTPError specifies the error code, enhanced error code (if any) and message returned by the server.
Backend and Session methods should return an *SMTPError (or an error that wraps one) so the server sends a deliberate, well-formed status line. A plain error is surfaced to the client as "554 5.0.0 Error: transaction failed: <error text>", which leaks the raw internal message — return an *SMTPError, for example via Errorf, to choose the status code and message instead.
func Errorf ¶ added in v0.27.0
func Errorf(code int, enhancedCode EnhancedCode, format string, a ...interface{}) *SMTPError
Errorf returns an *SMTPError with the given SMTP status code, enhanced status code, and a message formatted per fmt.Sprintf. It is a convenience for backends, which should return an *SMTPError so the server sends the chosen status line rather than leaking a raw error (see SMTPError).
Errorf is not only for failures: returning an *SMTPError whose Code is in the 2xx range from Mail, Rcpt or Data sets a custom non-failure status line in place of the server's default (for example the "250 ... OK: queued" after the final dot). The transaction proceeds exactly as if nil had been returned; only the status text differs. This is the additive way to customize a success response, since those methods can only communicate back through their error return.
type Server ¶
type Server struct {
// The type of network, "tcp" or "unix".
Network string
// TCP or Unix address to listen on.
Addr string
// The server TLS configuration.
TLSConfig *tls.Config
// Enable LMTP mode, as defined in RFC 2033.
LMTP bool
Domain string
MaxRecipients int
MaxMessageBytes int64
MaxLineLength int
AllowInsecureAuth bool
Debug io.Writer
ErrorLog Logger
ReadTimeout time.Duration
WriteTimeout time.Duration
// Advertise SMTPUTF8 (RFC 6531) capability.
// Should be used only if backend supports it.
EnableSMTPUTF8 bool
// Advertise REQUIRETLS (RFC 8689) capability.
// Should be used only if backend supports it.
EnableREQUIRETLS bool
// Advertise BINARYMIME (RFC 3030) capability.
// Should be used only if backend supports it.
EnableBINARYMIME bool
// Advertise DSN (RFC 3461) capability.
// Should be used only if backend supports it.
EnableDSN bool
// Advertise RRVS (RFC 7293) capability.
// Should be used only if backend supports it.
EnableRRVS bool
// Advertise DELIVERBY (RFC 2852) capability.
// Should be used only if backend supports it.
EnableDELIVERBY bool
// The minimum time, with seconds precision, that a client
// may specify in the BY argument with return mode.
// A zero value indicates no set minimum.
// Only use if DELIVERBY is enabled.
MinimumDeliverByTime time.Duration
// Advertise MT-PRIORITY (RFC 6710) capability.
// Should only be used if backend supports it.
EnableMTPRIORITY bool
// The priority profile mapping as defined
// in RFC 6710 section 10.2.
//
// Default value of NONE to advertise no specific profile.
MtPriorityProfile PriorityProfile
// Additional capabilities to advertise in response to EHLO, e.g.
// "XEXAMPLE https://example.org/smtp-ext". Each entry is advertised
// verbatim as a separate capability line.
//
// This can be used to advertise site-specific extensions that are not
// natively supported by this package. It is the caller's responsibility
// to handle any commands such an extension defines.
ExtraCaps []string
// EnableXCLIENT advertises and honors the XCLIENT extension, which lets a
// trusted proxy (haproxy/nginx/Postfix) assert the real client's identity
// (ADDR/NAME/PROTO/HELO/LOGIN) on behalf of the connection.
//
// XCLIENT is only advertised and honored on connections for which
// TrustXCLIENT returns true. Without a TrustXCLIENT that returns true it is
// never honored — allowing an untrusted peer to assert XCLIENT would let it
// spoof any client identity.
EnableXCLIENT bool
// TrustXCLIENT reports whether the peer on the given connection is a trusted
// proxy permitted to assert client identity via XCLIENT. It is required for
// XCLIENT to have any effect and is typically an IP/CIDR or TLS-client-cert
// check against the connection's peer.
TrustXCLIENT func(*Conn) bool
// The server backend.
Backend Backend
// ConnState, if non-nil, is called when a client connection changes state:
// StateNew when it is accepted (before the greeting) and StateClosed when it
// is torn down. It mirrors net/http.Server.ConnState and is a single place to
// hook connection-level metrics, logging and debugging. It must not block.
ConnState func(net.Conn, ConnState)
// contains filtered or unexported fields
}
A SMTP server.
Example ¶
ExampleServer runs an example SMTP server.
It can be tested manually with e.g. netcat:
> netcat -C localhost 1025 EHLO localhost AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk MAIL FROM:<root@nsa.gov> RCPT TO:<root@gchq.gov.uk> DATA Hey <3 .
package main
import (
"errors"
"io"
"log"
"time"
"github.com/emersion/go-sasl"
"github.com/rest-mail/go-smtp"
)
// The Backend implements SMTP server methods.
type Backend struct{}
// NewSession is called after client greeting (EHLO, HELO).
func (bkd *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
return &Session{}, nil
}
// A Session is returned after successful login.
type Session struct {
auth bool
}
// AuthMechanisms returns a slice of available auth mechanisms; only PLAIN is
// supported in this example.
func (s *Session) AuthMechanisms() []string {
return []string{sasl.Plain}
}
// Auth is the handler for supported authenticators.
func (s *Session) Auth(mech string) (sasl.Server, error) {
return sasl.NewPlainServer(func(identity, username, password string) error {
if username != "username" || password != "password" {
return errors.New("Invalid username or password")
}
s.auth = true
return nil
}), nil
}
func (s *Session) Mail(from string, opts *smtp.MailOptions) error {
if !s.auth {
return smtp.ErrAuthRequired
}
log.Println("Mail from:", from)
return nil
}
func (s *Session) Rcpt(to string, opts *smtp.RcptOptions) error {
if !s.auth {
return smtp.ErrAuthRequired
}
log.Println("Rcpt to:", to)
return nil
}
func (s *Session) Data(r io.Reader) error {
if !s.auth {
return smtp.ErrAuthRequired
}
if b, err := io.ReadAll(r); err != nil {
return err
} else {
log.Println("Data:", string(b))
}
return nil
}
func (s *Session) Reset() {}
func (s *Session) Logout() error {
return nil
}
// ExampleServer runs an example SMTP server.
//
// It can be tested manually with e.g. netcat:
//
// > netcat -C localhost 1025
// EHLO localhost
// AUTH PLAIN
// AHVzZXJuYW1lAHBhc3N3b3Jk
// MAIL FROM:<root@nsa.gov>
// RCPT TO:<root@gchq.gov.uk>
// DATA
// Hey <3
// .
func main() {
be := &Backend{}
s := smtp.NewServer(be)
s.Addr = "localhost:1025"
s.Domain = "localhost"
s.WriteTimeout = 10 * time.Second
s.ReadTimeout = 10 * time.Second
s.MaxMessageBytes = 1024 * 1024
s.MaxRecipients = 50
s.AllowInsecureAuth = true
log.Println("Starting server at", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
Output:
func (*Server) Close ¶
Close immediately closes all active listeners and connections.
Close returns any error returned from closing the server's underlying listener(s).
func (*Server) ListenAndServe ¶
ListenAndServe listens on the network address s.Addr and then calls Serve to handle requests on incoming connections.
If s.Addr is blank and LMTP is disabled, ":smtp" is used.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS listens on the TCP network address s.Addr and then calls Serve to handle requests on incoming TLS connections.
If s.Addr is blank and LMTP is disabled, ":smtps" is used.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).
type Session ¶
type Session interface {
// Discard currently processed message.
Reset()
// Free all resources associated with session.
Logout() error
// Set return path for currently processed message.
Mail(from string, opts *MailOptions) error
// Add recipient for currently processed message.
Rcpt(to string, opts *RcptOptions) error
// Set currently processed message contents and send it.
//
// r must be consumed before Data returns.
Data(r io.Reader) error
}
Session is used by servers to respond to an SMTP client.
The methods are called when the remote client issues the matching command.
type StatusCollector ¶
StatusCollector allows a backend to provide per-recipient status information.
type XClientAttrs ¶ added in v0.27.0
type XClientAttrs struct {
Addr string // real client IP address (ADDR)
Name string // real client reverse-DNS name (NAME)
Proto string // client protocol (PROTO), e.g. "SMTP" or "ESMTP"
Helo string // client HELO/EHLO name (HELO)
Login string // authenticated username (LOGIN)
}
XClientAttrs holds the client identity a trusted proxy asserted via the XCLIENT extension. Empty fields were not asserted.