Standard library / net/smtp
smtp.Client
Represent a stateful SMTP session. Use methods in protocol order and close the connection on completion. Text exposes the underlying textproto connection for extensions. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
type Client struct { Text *textproto.Conn
}Working Example
Example Snippetgo
package main
import ( "bufio" "crypto/tls" "crypto/x509" "encoding/base64" "fmt" "io" "net" "net/http" "net/http/httptest" "net/smtp" "strings" "time")
func main() { addr, _, done := fixture(false) defer done() c := must(smtp.Dial(addr)) defer c.Close() fmt.Println(c.Text != nil) check(c.Quit())}
// A disposable loopback SMTP responder, not a production mail server.// It accepts only synthetic messages and never relays them.func fixture(secure bool) (string, *tls.Config, func()) { var serverTLS, clientTLS *tls.Config if secure { ts := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) serverTLS = ts.TLS.Clone() roots := x509.NewCertPool() roots.AddCert(ts.Certificate()) clientTLS = &tls.Config{RootCAs: roots, ServerName: "127.0.0.1", MinVersion: tls.VersionTLS12} ts.Close() } l := must(net.Listen("tcp4", "127.0.0.1:0")) check(l.(*net.TCPListener).SetDeadline(time.Now().Add(5 * time.Second))) done := make(chan struct{}) go func() { defer close(done) c, e := l.Accept() if e != nil { return } defer c.Close() check(c.SetDeadline(time.Now().Add(5 * time.Second))) var conn net.Conn = c r := bufio.NewReader(conn) send := func(s string) { _, _ = io.WriteString(conn, s+"\r\n") } send("220 fixture.invalid ESMTP") encrypted := false for { line, e := r.ReadString('\n') if e != nil { return } line = strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r") cmd := strings.Fields(line) if len(cmd) == 0 { return } switch cmd[0] { case "EHLO": send("250-fixture.invalid") send("250-8BITMIME") send("250-SMTPUTF8") if secure && !encrypted { send("250-STARTTLS") } send("250 AUTH PLAIN") case "HELO", "MAIL", "RCPT", "NOOP", "RSET": send("250 ok") case "VRFY": send("252 cannot verify") case "AUTH": if line == "AUTH PLAIN "+base64.StdEncoding.EncodeToString([]byte("\x00demo\x00synthetic")) { send("235 ok") } else { send("535 rejected") } case "DATA": send("354 finish with dot") for { s, e := r.ReadString('\n') if e != nil { return } if s == ".\r\n" { break } } send("250 accepted locally") case "STARTTLS": if !secure || encrypted { send("454 unavailable") continue } send("220 ready") t := tls.Server(conn, serverTLS) if t.Handshake() != nil { return } conn = t r = bufio.NewReader(conn) encrypted = true case "QUIT": send("221 bye") return default: send("500 unsupported") } } }() return l.Addr().String(), clientTLS, func() { l.Close(); <-done }}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}