Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 147 ยท Web and Networking

Sending Email with net/smtp

Send email from Go with net/smtp - PlainAuth, SendMail, message headers, HTML and attachments with MIME multipart, and a local SMTP server you can run in the lesson to see the real conversation.

Almost every web application sends email: a welcome message, a password reset link, an order receipt. Go's standard library has had an SMTP client since version 1, in the package net/smtp, and the packages net/mail, mime and mime/multipart help you build well-formed messages. You can send a plain-text email in about ten lines.

This lesson shows what SMTP actually says on the wire, how to use smtp.SendMail and smtp.PlainAuth, how to write correct headers and an HTML-plus-text message, and how to test your code without ever contacting a real mail server. The site's code runner has no outside network, so every example talks to a small SMTP server that the program starts itself on the loopback address.

The net/smtp package is frozen: it still works and is stable, but the Go team accepts no new features for it. For production mail, most projects either use it directly for simple cases or call the HTTP API of a mail provider (which also gives delivery tracking), and a few use third-party client libraries for features such as connection reuse and attachments.

How SMTP works

SMTP (Simple Mail Transfer Protocol) is a text conversation over TCP, usually on port 25 (server to server), 587 (submission, STARTTLS) or 465 (implicit TLS). The client sends a command, the server answers with a three-digit code:

TEXT
S: 220 mail.example.com ready
C: EHLO myhost
S: 250-mail.example.com
S: 250 AUTH PLAIN
C: AUTH PLAIN <base64 of "\0user\0password">
S: 235 authenticated
C: MAIL FROM:<[email protected]>
S: 250 ok
C: RCPT TO:<[email protected]>
S: 250 ok
C: DATA
S: 354 end with a line containing only a dot
C: (headers, blank line, body)
C: .
S: 250 queued
C: QUIT
S: 221 bye

Two ideas matter. The envelope (MAIL FROM, RCPT TO) says who the mail is really from and to; the headers inside DATA (From:, To:) are what the recipient's mail program shows. They are independent, which is why Bcc works: the address is in the envelope but not in the headers.

A local SMTP server for experiments

To see the conversation, the next program starts a tiny SMTP server in a goroutine on 127.0.0.1 with a random port. It logs every command the client sends and stores each received message. You will reuse the same helper in later examples.

Go Sending mail to a local stand-in server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You see the client's commands: EHLO localhost, AUTH PLAIN followed by a base64 blob (decode it and you get the user name and password, which is why PLAIN needs TLS), MAIL FROM:<[email protected]>, RCPT TO:<[email protected]>, DATA and QUIT. The helper does not log the message lines between DATA and the lone .. Then SendMail error: <nil> and server stored 1 message.

Three details deserve attention. smtp.SendMail(addr, auth, from, to, msg) does everything in one call: connect, EHLO, upgrade with STARTTLS when the server offers it, authenticate, send, and QUIT. The msg must use \r\n line endings, not bare \n. And PlainAuth refuses to send your password over an unencrypted connection to a remote host; it only allows it for localhost, 127.0.0.1 or ::1, which is why this test works and a real server must offer TLS. The first argument of PlainAuth is an "identity" (usually empty), and the last is the server's host name, which the library compares with the host it connected to so credentials cannot be redirected.

Headers: getting the message right

The message is headers, a blank line, then a body. The headers that matter:

Header Purpose
From, To, Cc Shown to the reader; Bcc is never written to the headers
Subject Must be encoded if it contains non-ASCII characters
Date RFC 1123 format, time.Now().Format(time.RFC1123Z)
Message-ID Unique id, helps threading and de-duplication
MIME-Version: 1.0 Required when you use content types
Content-Type text/plain; charset=UTF-8 or text/html; charset=UTF-8 or multipart/...

Never paste user input into a header without cleaning it. A subject such as Hi\r\nBcc: [email protected] would add a header: this is header injection, and it is how contact forms get turned into spam relays. Reject any header value that contains \r or \n. Use net/mail for addresses, since mail.ParseAddress validates them and Address.String() encodes display names correctly. mime.QEncoding.Encode("utf-8", subject) produces a safe encoded subject for non-ASCII text.

Go Building a safe plain-text message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The parsed address prints with its name quoted ("Bob" <[email protected]>), and the display name Ada Cafรฉ is encoded in the From line as =?utf-8?q?Ada_Caf=C3=A9?= <[email protected]>, the subject becomes an encoded word too, and the Date header reads Thu, 05 Mar 2026 09:30:00 +0000. The last call fails with header Subject contains a line break, which stops the injection before anything is sent.

HTML, plain text and attachments with MIME

A message with both a plain-text and an HTML version uses multipart/alternative; a message with attachments uses multipart/mixed. The mime/multipart writer creates the boundaries for you. Mail clients show the last alternative they understand, so write the plain text first and the HTML second. Binary data such as a PDF is attached as base64 with a Content-Disposition: attachment header.

Go An HTML and text message with an attachment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output shows the structure: an outer MIXEDBOUNDARY with two parts, the first being a nested multipart/alternative that holds the plain and HTML bodies, the second the report.csv attachment as base64 (aWQsdG90YWwK...). In a complete message you would put MIME-Version: 1.0 and this Content-Type in the headers, then a blank line, then the body.

Putting it together and testing

Real code should hide the transport behind a small interface, so tests and local development never touch a real server (compare interface design):

Go A Mailer interface with SMTP and in-memory versions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The fake collects [[email protected]: Welcome! [email protected]: Welcome!], and the real mailer returns real mailer error: 550 "no such user"; the server's reply code and text come straight from the *textproto.Error that net/smtp returns. Use errors.As with *textproto.Error to read the numeric code: 4xx means a temporary failure worth retrying later, 5xx a permanent one.

Some practical rules for production:

  • Do not send mail inside the HTTP request handler. SMTP servers can be slow or down. Put the email on a queue or background worker and retry temporary failures with backoff.
  • Keep credentials out of code. Read them from environment variables or a secret store.
  • Use port 587 with STARTTLS or port 465 with implicit TLS. SendMail upgrades automatically when the server announces STARTTLS; for port 465 you dial with crypto/tls yourself and use smtp.NewClient. See TLS and HTTPS.
  • Set up SPF, DKIM and DMARC DNS records for your sending domain, or your mail will land in spam no matter how well your code works.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What line ending must an SMTP message use?

    SMTP is defined with CRLF line endings. Bare \n can be rejected or rewritten by servers.
  2. 2. Why does PlainAuth refuse to work against a remote server on an unencrypted connection?

    AUTH PLAIN only base64-encodes the credentials. PlainAuth therefore requires TLS unless the host is localhost.
  3. 3. A contact form puts the visitor's input into the Subject header. What is the main risk?

    A line break in a header value starts a new header. Reject or strip \r and \n from every value that goes into a header.
  4. 4. Which multipart type holds a text version and an HTML version of the same message?

    multipart/alternative lists different representations of the same content; clients display the best one they support.

Summary

  • SMTP is a text conversation: EHLO, optional STARTTLS and AUTH, MAIL FROM, RCPT TO, DATA, QUIT. The envelope and the headers are separate.
  • smtp.SendMail with smtp.PlainAuth covers the simple case; messages use \r\n line endings.
  • Build headers carefully: validate addresses with net/mail, encode non-ASCII with mime, and reject line breaks in values.
  • Use mime/multipart for text plus HTML (multipart/alternative) and attachments (multipart/mixed).
  • Hide sending behind an interface so tests use a fake, and send mail from a background worker rather than the request path.
  • net/smtp is frozen; for large-scale sending, a provider's API is often the better tool.

Next: Databases with database/sql opens the Databases chapter.