New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

Go Send Email with SMTP: net/smtp, STARTTLS, TLS and Timeouts

Send email from Go with net/smtp: PlainAuth, SendMail, STARTTLS and implicit TLS, building MIME messages with HTML and attachments, adding timeouts, preventing header injection and handling errors.

MO
Written by Mateus Oliveira
Senior SMTP and MTA Engineer
Reviewed by Tomasz Kowalski
  • Published30 Jun 2026
  • Read time8 min
  • Length1,695 words
Share this guide

Go's standard library includes net/smtp, a small SMTP client that is enough for many services. It also has sharp edges: smtp.SendMail has no timeout, it only upgrades to TLS when the server offers STARTTLS, it does not speak implicit TLS on port 465, and it does not build the message for you. The package documentation describes it as frozen, so new features go into community libraries instead. This guide shows how to use the standard library correctly: authenticate, send with SendMail, connect with explicit control for timeouts and TLS, build a proper MIME message with HTML and an attachment, avoid header injection and read the errors you get back. It also explains when a library such as go-mail is worth the dependency. The examples use placeholders. Take real values from your SMTP provider's dashboard and read secrets from the environment.

Authsmtp.PlainAuth(identity, user, password, host)
Simple sendsmtp.SendMail upgrades with STARTTLS when offered
Controlnet.Dialer + smtp.NewClient for timeouts and port 465
MessageBuild headers and MIME parts yourself

The shortest working example

With port 587 and a server that offers STARTTLS, smtp.SendMail is enough for a plain-text message. The host passed to PlainAuth must match the server name, and PlainAuth refuses to send the password over an unencrypted connection unless the server is localhost, which protects you from a downgrade.

package main

import (
    "fmt"
    "log"
    "net/smtp"
    "os"
)

func main() {
    host := os.Getenv("SMTP_HOST") // e.g. smtp.example.com
    user := os.Getenv("SMTP_USER")
    pass := os.Getenv("SMTP_PASSWORD")

    auth := smtp.PlainAuth("", user, pass, host)

    msg := []byte("From: Example App <[email protected]>\r\n" +
        "To: [email protected]\r\n" +
        "Subject: Test message\r\n" +
        "\r\n" +
        "This is a test.\r\n")

    err := smtp.SendMail(host+":587", auth, "[email protected]",
        []string{"[email protected]"}, msg)
    if err != nil {
        log.Fatalf("send failed: %v", err)
    }
    fmt.Println("sent")
}

Note that the envelope sender and recipients are separate arguments from the headers in the message. The envelope decides where the message goes; the To header is only what the recipient's client displays. Lines in SMTP end with CRLF, so use \r\n, and separate the headers from the body with one empty line.

Why SendMail is not enough for production

There are three problems. First, it has no timeout: if the port is blocked or the server stalls, the call waits for the operating system to give up, which can be minutes. Second, it uses STARTTLS only if the server advertises it, and otherwise continues without encryption, although PlainAuth will then refuse to send the password. Third, it cannot do implicit TLS on port 465 because it begins in plain text. For production, take control of the connection.

Connect with timeouts and STARTTLS

func dialSTARTTLS(host string, port int, user, pass string) (*smtp.Client, error) {
    addr := fmt.Sprintf("%s:%d", host, port)
    d := net.Dialer{Timeout: 10 * time.Second}
    conn, err := d.Dial("tcp", addr)
    if err != nil {
        return nil, err
    }
    conn.SetDeadline(time.Now().Add(30 * time.Second)) // whole conversation

    c, err := smtp.NewClient(conn, host)
    if err != nil {
        conn.Close()
        return nil, err
    }
    if ok, _ := c.Extension("STARTTLS"); !ok {
        c.Close()
        return nil, errors.New("server does not offer STARTTLS")
    }
    if err := c.StartTLS(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}); err != nil {
        c.Close()
        return nil, err
    }
    if err := c.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
        c.Close()
        return nil, err
    }
    return c, nil
}

This version fails closed: if the server does not offer STARTTLS, it returns an error instead of continuing. The dialer timeout limits the connection attempt, and the connection deadline bounds the whole conversation, so a stalled server cannot hold a goroutine for long. Keep ServerName set so that certificate verification checks the right name, and never set InsecureSkipVerify in production.

Implicit TLS on port 465

For port 465, open a TLS connection first and then wrap it in an SMTP client. Authentication and sending work the same way afterwards.

func dialTLS(host string, port int, user, pass string) (*smtp.Client, error) {
    addr := fmt.Sprintf("%s:%d", host, port)
    d := &net.Dialer{Timeout: 10 * time.Second}
    conn, err := tls.DialWithDialer(d, "tcp", addr,
        &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12})
    if err != nil {
        return nil, err
    }
    conn.SetDeadline(time.Now().Add(30 * time.Second))
    c, err := smtp.NewClient(conn, host)
    if err != nil {
        conn.Close()
        return nil, err
    }
    if err := c.Auth(smtp.PlainAuth("", user, pass, host)); err != nil {
        c.Close()
        return nil, err
    }
    return c, nil
}

Match the function to the port: STARTTLS for 587, implicit TLS for 465. A mismatch produces handshake errors or a hang. If you are unsure which port your network allows, read which SMTP port to use.

Send through the client

func send(c *smtp.Client, from string, to []string, msg []byte) error {
    defer c.Close()
    if err := c.Mail(from); err != nil {
        return err
    }
    for _, rcpt := range to {
        if err := c.Rcpt(rcpt); err != nil {
            return fmt.Errorf("recipient %s: %w", rcpt, err)
        }
    }
    w, err := c.Data()
    if err != nil {
        return err
    }
    if _, err := w.Write(msg); err != nil {
        return err
    }
    if err := w.Close(); err != nil {
        return err
    }
    return c.Quit()
}

The writer returned by Data() handles dot-stuffing for you, so you do not need to escape lines that begin with a period. Always check the error from w.Close(): the server's final verdict on the message arrives there, and ignoring it is how failed sends are reported as successes. You can also send several messages over one connection by calling c.Reset() between them.

Build a MIME message with HTML and an attachment

A real message needs encoded headers and MIME parts. The standard library gives you mime, mime/multipart and encoding/base64 for the job. The structure is a multipart/mixed body holding a multipart/alternative part (text and HTML) and then the attachment. Writing it correctly by hand takes about forty lines and is easy to get wrong: base64 lines must be wrapped at 76 characters, and each part needs the right headers. That is the point at which a library earns its place. github.com/wneessen/go-mail, for example, offers a message builder with text, HTML and attachments, connection options for STARTTLS and implicit TLS, and context-based timeouts. Choose the standard library for small tools and a library for products that send many different messages.

Whichever route you take, send both a plain-text and an HTML part, set a meaningful Subject encoded with mime.QEncoding.Encode("utf-8", subject) if it contains non-ASCII characters, and include a unique Message-ID and a Date header. Use simple inline-styled HTML; the HTML email template guide lists what renders reliably in mail clients.

Prevent header injection

If you build headers by concatenating strings, a user-supplied value that contains a line break can add headers, such as extra Bcc recipients, and turn your contact form into a spam relay. Reject any value used in a header or envelope that contains \r or \n. Parse addresses with net/mail.ParseAddress and use the parsed form. Libraries do this for you, but if you build messages yourself the check is your responsibility.

Read the errors

Errors returned by the SMTP client are often *textproto.Error values with a numeric Code and a Msg. Use errors.As to extract them. Codes from 400 to 499 are temporary and worth retrying later with backoff, and codes from 500 to 599 are permanent for that message. Network errors, such as timeouts, are usually temporary. The article on SMTP reply codes explains the numbers.

SymptomLikely causeFix
535 Authentication failedWrong credentials or empty environment variablesPrint whether the variables are set and re-copy them; see SMTP error 535
unencrypted connection from PlainAuthAuth attempted before TLS was establishedCall StartTLS first or use port 465 with implicit TLS
i/o timeout or hangBlocked outbound port, or no timeout setAdd dialer and connection deadlines; test the port from the same host
x509: certificate is valid for ...ServerName does not match the certificateUse the exact host from your provider
550 sender rejectedFrom address not on an authenticated domainSend from a verified domain
Delivered but in spamMissing authentication or poor reputationFollow the domain authentication guide

Test your Go mail code

Hide the sending code behind a small interface, such as a Sender with one Send(ctx, msg) method, so that handlers and jobs can be tested with a fake that records messages. For tests that exercise the SMTP conversation itself, run a tiny in-process server on a random local port, or a local mail catcher in a container, and point the client at it. Include tests for the failure paths, because that is where mail code usually breaks: a server that refuses the recipient, a connection that drops after DATA, and a login that fails. Check that your code returns an error in each case and that a failed message is kept for a retry, not dropped.

Deliverability reminders

A message that the server accepts can still end up in spam. Send from an address on a domain you have authenticated with SPF, DKIM and DMARC, include a plain-text part, avoid sending to addresses you know are invalid, and keep transactional mail on its own subdomain so that a problem with bulk mail cannot delay a one-time code. If a message is accepted but does not appear, the spam troubleshooting checklist is the next place to look.

Concurrency and retries

An smtp.Client is not safe for concurrent use, so give each worker goroutine its own connection and feed workers from a channel. Limit the number of workers to what your plan allows, and respect temporary failures by pausing instead of retrying instantly. Wrap each message in a context with a deadline, and write failed messages to a store with the reply code so they can be inspected later. The pattern in rate limits, retries and backoff applies directly. Before you ship, check the connection settings with the steps in how to test an SMTP connection, so that you know any failure is in the code and not in the network.

Send from Go through a managed relay Use the SMTP host and credentials from your dashboard and send your first message in minutes.

Explore the SMTP relay

References and further reading

Frequently asked questions

Does Go net/smtp support port 465?

Not through SendMail, which begins in plain text. Open a connection with crypto/tls first and wrap it with smtp.NewClient.

Why does smtp.PlainAuth say unencrypted connection?

PlainAuth refuses to send the password over a connection that is not encrypted, unless the host is localhost. Use STARTTLS or implicit TLS first.

How do I add a timeout to Go SMTP?

Dial with net.Dialer and a Timeout, set a connection deadline, then create the client with smtp.NewClient instead of using SendMail.

Should I use net/smtp or a library?

The standard library is fine for small tools. For HTML, attachments, and many message types, a maintained library such as go-mail saves time and avoids MIME mistakes.

How do I stop header injection in Go email code?

Reject values that contain CR or LF before using them in headers or the envelope, and parse addresses with net/mail.ParseAddress.

Topics#go#golang#smtp#net/smtp#developers
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales