Documentation ¶
Overview ¶
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
It also implements the following extensions:
8BITMIME: RFC 1652 AUTH: RFC 2554 STARTTLS: RFC 3207 ENHANCEDSTATUSCODES: RFC 2034 SMTPUTF8: RFC 6531 REQUIRETLS: RFC 8689 CHUNKING: RFC 3030 BINARYMIME: RFC 3030
LMTP (RFC 2033) is also supported.
Additional extensions may be handled by other packages.
Index ¶
- Variables
- func SendMail(addr string, a sasl.Client, from string, to []string, r io.Reader) error
- type Backend
- type BodyType
- type Client
- func (c *Client) Auth(a sasl.Client) error
- func (c *Client) Close() error
- func (c *Client) Data() (io.WriteCloser, error)
- func (c *Client) Extension(ext string) (bool, string)
- func (c *Client) GetConn() net.Conn
- func (c *Client) Hello(localName string) error
- func (c *Client) LMTPData(statusCb func(rcpt string, status *SMTPError)) (io.WriteCloser, error)
- func (c *Client) Mail(from string, opts *MailOptions) error
- func (c *Client) Noop() error
- func (c *Client) Quit() error
- func (c *Client) Rcpt(to string) error
- func (c *Client) Reset() error
- func (c *Client) StartTLS(config *tls.Config) error
- func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
- func (c *Client) Verify(addr string) error
- func (c *Client) XClient(xc XClientOptions) error
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) GetConn() net.Conn
- func (c *Conn) ReadLine() (string, error)
- func (c *Conn) Reject()
- func (c *Conn) Server() *Server
- func (c *Conn) Session() Session
- func (c *Conn) SetLineLimit(limit int)
- func (c *Conn) SetSession(session Session)
- func (c *Conn) State() ConnectionState
- func (c *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool)
- func (c *Conn) WriteResponse(code int, enhCode EnhancedCode, text ...string)
- func (c *Conn) XClientState() XClientOptions
- type ConnectionAwareBackend
- type ConnectionAwareSession
- type ConnectionState
- type EnhancedCode
- type LMTPSession
- type Logger
- type MailOptions
- type SMTPError
- type SaslServerFactory
- type Server
- func (s *Server) Close() error
- func (s *Server) DisableAuth(name string)
- func (s *Server) EnableAuth(name string, f SaslServerFactory)
- func (s *Server) ForEachConn(f func(*Conn))
- func (s *Server) ListenAndServe() error
- func (s *Server) ListenAndServeTLS() error
- func (s *Server) Serve(l net.Listener) error
- type Session
- type StatusCollector
- type XClientOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrAuthRequired = errors.New("please authenticate first") ErrAuthUnsupported = errors.New("authentication not supported") )
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 ErrTooLongLine = errors.New("smtp: too longer 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 SendMail ¶
SendMail connects to the server at addr, switches to TLS if possible, authenticates with the optional mechanism a if possible, 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 ¶
// 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:
Types ¶
type Backend ¶
type Backend interface { // Authenticate a user. Return smtp.ErrAuthUnsupported if you don't want to // support this. Login(state *ConnectionState, username, password string) (Session, error) // Called if the client attempts to send mail without logging in first. // Return smtp.ErrAuthRequired if you don't want to support this. AnonymousLogin(state *ConnectionState) (Session, error) }
A SMTP server backend.
type Client ¶
type Client struct { // Text is the textproto.Conn used by the Client. It is exported to allow for // clients to add extensions. Text *textproto.Conn // 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".
Example ¶
// 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"); 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 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 connector and host as a server name to be used when authenticating.
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) Data ¶
func (c *Client) Data() (io.WriteCloser, 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.
If server returns an error, it will be of type *SMTPError.
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) LMTPData ¶
LMTPData is the LMTP-specific version of the Data method. It accepts a callback that will be called for each status response received from the server.
Status callback will receive a SMTPError argument for each negative server reply and nil for each positive reply. I/O errors will not be reported using callback and instead will be returned by the Close method of io.WriteCloser. Callback will be called for each successfull Rcpt call done before in the same order.
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) Noop ¶
Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.
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 ¶
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 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) StartTLS ¶
StartTLS sends the STARTTLS command and encrypts all further communication. Only servers that advertise the STARTTLS extension support this function.
A nil config is equivalent to a zero tls.Config.
If server returns an error, it will be of type *SMTPError.
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.
func (*Client) XClient ¶ added in v0.16.0
func (c *Client) XClient(xc XClientOptions) error
Xclient issues an XCLIENT command to the server with the provided options. Only non-nil filled options that are supported by the server are sent. Note: Some parameters are (pointers to) strings. There is no check if those parameters have the correct value. Specifically, if they contain whitespace then the result is undefined.
type Conn ¶
func (*Conn) SetLineLimit ¶ added in v0.16.0
SetLineLimit sets the internal line limit of the SMTP connection. Set to 0 to disable line limits.
func (*Conn) SetSession ¶
Setting the user resets any message being generated
func (*Conn) State ¶
func (c *Conn) State() ConnectionState
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) WriteResponse ¶
func (c *Conn) WriteResponse(code int, enhCode EnhancedCode, text ...string)
func (*Conn) XClientState ¶ added in v0.16.0
func (c *Conn) XClientState() XClientOptions
type ConnectionAwareBackend ¶ added in v0.16.0
type ConnectionAwareBackend interface { // Called as soon as a connection comes in IncomingConnection(c *Conn) (Session, error) }
A more modern SMTP server backend.
type ConnectionAwareSession ¶ added in v0.16.0
type ConnectionAwareSession interface { // Called as the HELO comes in, optionally returns welcome string Hello(c ConnectionState, name string) (*string, error) }
type ConnectionState ¶
type EnhancedCode ¶
type EnhancedCode [3]int
type LMTPSession ¶
type LMTPSession interface { // 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 int // 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 // 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 custom arguments that were passed as an argument to the MAIL 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.
type SaslServerFactory ¶
type SaslServerFactory func(conn *Conn) sasl.Server
A function that creates SASL servers.
type Server ¶
type Server struct { // 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 mode cannot be used with a // TCP listener. LMTP bool Domain string MaxRecipients int MaxMessageBytes int MaxLineLength int AllowInsecureAuth bool Strict 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 // If set, the AUTH command will not be advertised and authentication // attempts will be rejected. This setting overrides AllowInsecureAuth. AuthDisabled bool // If set, do not advertise PIPELINING (RFC2920) capability. // Note that this doesn't change anything about the internal processing, // which always allows pipelining. PipeliningDisabled bool // If set, do not advertise 8BITMIME (rfc6152) capability. EightbitmimeDisabled bool // If set, do not advertise ENHANCEDSTATUSCODES (rfc2034) capability. // This also prevents enhanced status codes from being included in error messages. EnhancedStatusDisabled bool // If set, disable CHUNKING (rfc3030) capability. ChunkingDisabled bool // The server backend. Backend Backend // contains filtered or unexported fields }
A SMTP server.
func NewServer ¶
New creates a new SMTP server.
Example ¶
be := &Backend{} s := smtp.NewServer(be) s.Addr = ":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) DisableAuth ¶ added in v0.16.0
DisableAuth disables an autnetication mechanism. Should only be used to disable the default PLAIN mechanism that is enabled by default by the NewServer method.
func (*Server) EnableAuth ¶
func (s *Server) EnableAuth(name string, f SaslServerFactory)
EnableAuth enables an authentication mechanism on this server.
This function should not be called directly, it must only be used by libraries implementing extensions of the SMTP protocol.
func (*Server) ForEachConn ¶
ForEachConn iterates through all opened connections.
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, ":smtps" is used.
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) error // Set currently processed message contents and send it. 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 XClientOptions ¶ added in v0.16.0
type XClientOptions struct { // Name is the name of the connecting client, usually from reverse DNS lookup Name *string // Addr is the remote IP address Addr *net.IP // Port is the remote TCP client port Port *uint32 // Proto is either "SMTP" or "ESMTP" Proto *string // Helo is the remote name sent via the HELO (EHLO) command Helo *string // Login is a SASL login name Login *string // Destaddr is the original destination IP address Destaddr *net.IP // Destport is the original destination port number Destport *uint32 }
XClientOptions are options that are used on the XCLIENT extension
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package backendutil provide utilities to implement SMTP backends.
|
Package backendutil provide utilities to implement SMTP backends. |
cmd
|
|