How to Send Email in Go: net/smtp, Gin and API
Pranav Patel
Co-founderยท13 min read
On this page

Send email from Go with net/smtp, go-mail, Gin or net/http, or with an email API. Copy-paste examples for HTML email, attachments, background workers and retries without duplicates.
Go can send email with the built-in net/smtp package, no install needed. For anything in production, send through a provider: either over SMTP with net/smtp or a library like go-mail, or over HTTPS with an email API SDK.
This guide covers plain net/smtp, the Reloop Go SDK, Gin and net/http, then the production details: attachments, background sending and safe retries.
Working in another language? See how to send email in Python or Node.js.
Which approach should you use?
net/smtp / go-mailnet/smtp, it is in the standard librarygo get github.com/reloop-labs/reloop-go/v2SendMailParams struct with HTML, Text, Attachments*textproto.Error with an SMTP code*reloop.APIError with an HTTP statusIf a tool or library you do not control only speaks SMTP, use SMTP. If you are writing the send call yourself, use the API.
Prerequisites
- Go 1.25 or later. The Reloop SDK supports Go 1.20, but current Gin and go-mail releases need 1.25.
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment or a secrets manager, never in your code or git.
Method 1: Send email with net/smtp
net/smtp sends bytes. You build the headers and the MIME body yourself. The mime/multipart package handles the boundaries, so a plain-text and HTML email looks like this:
1package main2
3import (4 "bytes"5 "fmt"6 "log"7 "mime"8 "mime/multipart"9 "net/smtp"10 "net/textproto"11 "os"12 "time"13)14
15func main() {16 from := "Acme <hello@mail.acme.com>"17 to := "user@example.com"18 subject := "Welcome to Acme"19
20 // Build a multipart/alternative body: plain text first, then HTML21 var body bytes.Buffer22 mw := multipart.NewWriter(&body)23
24 textPart, _ := mw.CreatePart(textproto.MIMEHeader{25 "Content-Type": {"text/plain; charset=UTF-8"},26 })27 textPart.Write([]byte("Welcome! Thanks for signing up."))28
29 htmlPart, _ := mw.CreatePart(textproto.MIMEHeader{30 "Content-Type": {"text/html; charset=UTF-8"},31 })32 htmlPart.Write([]byte("<h1>Welcome!</h1><p>Thanks for signing up.</p>"))33 mw.Close()34
35 var msg bytes.Buffer36 fmt.Fprintf(&msg, "From: %s\r\n", from)37 fmt.Fprintf(&msg, "To: %s\r\n", to)38 fmt.Fprintf(&msg, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", subject))39 fmt.Fprintf(&msg, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))40 fmt.Fprintf(&msg, "MIME-Version: 1.0\r\n")41 fmt.Fprintf(&msg, "Content-Type: multipart/alternative; boundary=%s\r\n\r\n", mw.Boundary())42 msg.Write(body.Bytes())43
44 auth := smtp.PlainAuth("", "reloop", os.Getenv("RELOOP_API_KEY"), "smtp.reloop.sh")45
46 err := smtp.SendMail(47 "smtp.reloop.sh:587",48 auth,49 "hello@mail.acme.com", // envelope sender: the bare address50 []string{to},51 msg.Bytes(),52 )53 if err != nil {54 log.Fatal(err)55 }56}The username can be any string. The password is your API key.
smtp.SendMail upgrades the connection with STARTTLS when the server offers it, and PlainAuth refuses to send your key over an unencrypted connection to anything other than localhost. The envelope sender (third argument) is the bare address. The display name goes in the From: header.
net/smtp is frozen and gets no new features. It also has no timeout: SendMail can block for as long as the network lets it. That is fine for a script. In a server, use go-mail (below) or dial with net.DialTimeout and drive smtp.NewClient yourself.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the address changes:
err := smtp.SendMail("smtp.reloop.sh:2587", auth, "hello@mail.acme.com", []string{to}, msg.Bytes())Reloop does not offer implicit TLS on port 465, so do not wrap the connection in tls.Dial before the SMTP handshake. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
Server replies come back as *textproto.Error with the SMTP code. Anything else is a network, DNS or TLS problem:
1if err != nil {2 var smtpErr *textproto.Error3 switch {4 case errors.As(err, &smtpErr) && smtpErr.Code == 535:5 log.Print("wrong API key")6 case errors.As(err, &smtpErr) && smtpErr.Code >= 500:7 log.Printf("rejected (%d): %s", smtpErr.Code, smtpErr.Msg)8 case errors.As(err, &smtpErr):9 log.Printf("temporary failure (%d), retry later: %s", smtpErr.Code, smtpErr.Msg)10 default:11 log.Printf("send failed: %v", err) // DNS, timeout, TLS12 }13}5xx codes are permanent: retrying sends the same rejected message. 4xx codes are temporary.
Use go-mail when you need more
For attachments, timeouts or anything beyond a simple body, go-mail is the maintained option. It builds the MIME message for you:
1package main2
3import (4 "log"5 "os"6 "time"7
8 "github.com/wneessen/go-mail"9)10
11func main() {12 m := mail.NewMsg()13 if err := m.From("Acme <hello@mail.acme.com>"); err != nil {14 log.Fatal(err)15 }16 if err := m.To("user@example.com"); err != nil {17 log.Fatal(err)18 }19 m.Subject("Welcome to Acme")20 m.SetBodyString(mail.TypeTextPlain, "Welcome! Thanks for signing up.")21 m.AddAlternativeString(mail.TypeTextHTML, "<h1>Welcome!</h1><p>Thanks for signing up.</p>")22
23 c, err := mail.NewClient("smtp.reloop.sh",24 mail.WithPort(587),25 mail.WithTLSPolicy(mail.TLSMandatory),26 mail.WithSMTPAuth(mail.SMTPAuthPlain),27 mail.WithUsername("reloop"),28 mail.WithPassword(os.Getenv("RELOOP_API_KEY")),29 mail.WithTimeout(30*time.Second),30 )31 if err != nil {32 log.Fatal(err)33 }34 if err := c.DialAndSend(m); err != nil {35 log.Fatal(err)36 }37}TLSMandatory fails the send if STARTTLS is not available, instead of falling back to plain text.
Can I send with Gmail from Go?
For a personal script, yes: use smtp.gmail.com:587 with an App Password and your Gmail address as the PlainAuth username. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the Go SDK
Install
go get github.com/reloop-labs/reloop-go/v2The SDK uses only the standard library.
Send an email
1package main2
3import (4 "errors"5 "fmt"6 "log"7 "os"8
9 reloop "github.com/reloop-labs/reloop-go/v2"10)11
12func main() {13 client, err := reloop.NewClient(reloop.ClientOptions{14 APIKey: os.Getenv("RELOOP_API_KEY"),15 })16 if err != nil {17 log.Fatal(err) // the API key is empty18 }19
20 res, err := client.Mail.Send(reloop.SendMailParams{21 From: "Acme <hello@mail.acme.com>",22 To: "user@example.com",23 Subject: "Welcome to Acme",24 HTML: reloop.String("<h1>Welcome!</h1><p>Thanks for signing up.</p>"),25 Text: reloop.String("Welcome! Thanks for signing up."),26 })27 if err != nil {28 var valErr *reloop.ValidationError29 var apiErr *reloop.APIError30 switch {31 case errors.As(err, &valErr):32 log.Fatalf("invalid %s: %s", valErr.Field, valErr.Message)33 case errors.As(err, &apiErr):34 log.Fatalf("failed (%d): %s %s", apiErr.Status, apiErr.Body.Message, apiErr.Body.Fix)35 default:36 log.Fatal(err)37 }38 }39
40 fmt.Println("Sent:", res.ID)41}Send returns (*SendMailResponse, error). There are two error types:
*reloop.ValidationErrormeans a required field (From,To,Subject) is missing. No request was made.*reloop.APIErrorcovers everything else.Statusis the HTTP status, andBodyholds the API'sMessage,Why,FixandLink. Network failures come back as anAPIErrorwith status0.
Optional string fields like HTML and Text are pointers. reloop.String turns a string literal into one.
Create the client once at startup and share it. It is safe to use from many goroutines. Send does not take a context.Context; it uses an http.Client with a 30 second timeout. To change the timeout or transport, pass your own with client.SetHTTPClient.
Send to several recipients
To, Cc, Bcc and ReplyTo accept either a string or a []string:
1_, err := client.Mail.Send(reloop.SendMailParams{2 From: "Acme <hello@mail.acme.com>",3 To: []string{"ada@example.com", "grace@example.com"},4 Cc: "team@acme.com",5 ReplyTo: "support@acme.com",6 Subject: "Your weekly report",7 Text: reloop.String("Here is your report."),8 Tags: []reloop.SendMailTag{9 {Name: "type", Value: "weekly_report"},10 },11})Every address in To sees the others. For personalized mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1_, err := client.Mail.Send(reloop.SendMailParams{2 From: "Acme <hello@mail.acme.com>",3 To: "user@example.com",4 Subject: "Welcome to Acme",5 Template: &reloop.SendMailTemplate{6 ID: "tmpl_welcome",7 Variables: map[string]interface{}{8 "first_name": "Ada",9 "plan": "Pro",10 },11 },12})The SDK requires Subject on every send, including template sends. See templates for variables and defaults.
Gin
The SDK client is safe for concurrent use, so create it in main and close over it in your handlers:
1package main2
3import (4 "log"5 "net/http"6 "os"7
8 "github.com/gin-gonic/gin"9 reloop "github.com/reloop-labs/reloop-go/v2"10)11
12type contactRequest struct {13 Email string `json:"email" binding:"required,email"`14 Message string `json:"message" binding:"required"`15}16
17func main() {18 client, err := reloop.NewClient(reloop.ClientOptions{19 APIKey: os.Getenv("RELOOP_API_KEY"),20 })21 if err != nil {22 log.Fatal(err)23 }24
25 r := gin.Default()26
27 r.POST("/contact", func(c *gin.Context) {28 var req contactRequest29 if err := c.ShouldBindJSON(&req); err != nil {30 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})31 return32 }33
34 res, err := client.Mail.Send(reloop.SendMailParams{35 From: "Acme Website <contact@mail.acme.com>",36 To: "support@acme.com",37 ReplyTo: req.Email,38 Subject: "New message from " + req.Email,39 Text: reloop.String(req.Message),40 })41 if err != nil {42 log.Printf("contact email failed: %v", err)43 c.JSON(http.StatusBadGateway, gin.H{"error": "Could not send message"})44 return45 }46
47 c.JSON(http.StatusOK, gin.H{"id": res.ID})48 })49
50 r.Run(":8080")51}The visitor's address goes in ReplyTo, never in From. You can only send from your verified domain, and putting someone else's domain in From fails DMARC.
To return before the email is sent, start a goroutine. Copy what you need out of the request first, and do not use c inside the goroutine:
1r.POST("/signup", func(c *gin.Context) {2 email := c.PostForm("email")3 // ... create the user ...4
5 go func() {6 _, err := client.Mail.Send(reloop.SendMailParams{7 From: "Acme <hello@mail.acme.com>",8 To: email,9 Subject: "Welcome to Acme",10 Text: reloop.String("Thanks for signing up."),11 })12 if err != nil {13 log.Printf("welcome email to %s failed: %v", email, err)14 }15 }()16
17 c.JSON(http.StatusOK, gin.H{"ok": true})18})A bare goroutine has no retries and is lost if the process exits. For emails that must arrive, use a worker or a queue (see below).
Plain net/http
Without a framework, the same handler works with the standard library. Go 1.22 and later route on method and path in http.ServeMux:
1mux := http.NewServeMux()2mux.HandleFunc("POST /contact", func(w http.ResponseWriter, r *http.Request) {3 var req struct {4 Email string `json:"email"`5 Message string `json:"message"`6 }7 if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Email == "" {8 http.Error(w, "invalid request", http.StatusBadRequest)9 return10 }11
12 res, err := client.Mail.Send(reloop.SendMailParams{13 From: "Acme Website <contact@mail.acme.com>",14 To: "support@acme.com",15 ReplyTo: req.Email,16 Subject: "New message from " + req.Email,17 Text: reloop.String(req.Message),18 })19 if err != nil {20 http.Error(w, "could not send message", http.StatusBadGateway)21 return22 }23
24 w.Header().Set("Content-Type", "application/json")25 json.NewEncoder(w).Encode(map[string]string{"id": res.ID})26})27
28log.Fatal(http.ListenAndServe(":8080", mux))Echo, Fiber and Chi look the same: one shared client, a handler that calls client.Mail.Send.
Attachments
With the SDK, pass base64 content:
1pdf, err := os.ReadFile("invoice-1042.pdf")2if err != nil {3 log.Fatal(err)4}5
6_, err = client.Mail.Send(reloop.SendMailParams{7 From: "Acme Billing <billing@mail.acme.com>",8 To: "user@example.com",9 Subject: "Your invoice #1042",10 Text: reloop.String("Your invoice is attached."),11 Attachments: []reloop.SendMailAttachment{{12 Filename: reloop.String("invoice-1042.pdf"),13 Content: base64.StdEncoding.EncodeToString(pdf),14 ContentType: reloop.String("application/pdf"),15 }},16})Over SMTP, building attachment MIME parts by hand with net/smtp is error-prone. Use go-mail instead:
m.AttachFile("invoice-1042.pdf")It sets the content type from the file extension and encodes the file for you. m.AttachReader does the same for data already in memory. Note that AttachFile returns nothing and silently skips a file it cannot find, so check the path first.
Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.
Send in the background
Sending inside a web request adds latency and fails the request when the provider is slow. Move it to a worker and retry the errors that can succeed later.
First, decide which errors to retry:
1func isRetryable(err error) bool {2 var apiErr *reloop.APIError3 if !errors.As(err, &apiErr) {4 return false // ValidationError: the same input fails every time5 }6 return apiErr.Status == 0 || apiErr.Status == 429 || apiErr.Status >= 5007}Retry network errors (status 0), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time.
A channel worker
Go makes an in-process queue easy: a buffered channel and a few goroutines reading from it.
1type Mailer struct {2 client *reloop.Client3 jobs chan reloop.SendMailParams4 wg sync.WaitGroup5}6
7func NewMailer(client *reloop.Client, workers int) *Mailer {8 m := &Mailer{client: client, jobs: make(chan reloop.SendMailParams, 1000)}9 for i := 0; i < workers; i++ {10 m.wg.Add(1)11 go m.work()12 }13 return m14}15
16// Enqueue returns immediately. It returns false if the buffer is full.17func (m *Mailer) Enqueue(p reloop.SendMailParams) bool {18 select {19 case m.jobs <- p:20 return true21 default:22 return false23 }24}25
26// Close stops accepting jobs and waits for queued ones to finish.27func (m *Mailer) Close() {28 close(m.jobs)29 m.wg.Wait()30}31
32func (m *Mailer) work() {33 defer m.wg.Done()34 for p := range m.jobs {35 m.sendWithRetry(p)36 }37}38
39func (m *Mailer) sendWithRetry(p reloop.SendMailParams) {40 backoff := time.Second41 for attempt := 1; attempt <= 5; attempt++ {42 _, err := m.client.Mail.Send(p)43 if err == nil {44 return45 }46 if !isRetryable(err) {47 log.Printf("email to %v failed, not retrying: %v", p.To, err)48 return49 }50 log.Printf("email to %v failed (attempt %d): %v", p.To, attempt, err)51 time.Sleep(backoff)52 backoff *= 253 }54}Create one Mailer at startup, call Enqueue from handlers, and call Close during graceful shutdown so queued emails finish.
Be honest about what this is: the queue lives in memory. A crash, deploy or OOM kill loses everything still in the channel. That is acceptable for low-stakes mail. For receipts, password resets and anything else that must arrive, use a persistent queue.
A persistent queue with River
River stores jobs in Postgres, so they survive restarts, and you can insert the job in the same transaction that creates the user. asynq is the Redis-based equivalent. With River, a worker looks like this:
1type WelcomeEmailArgs struct {2 Email string `json:"email"`3}4
5func (WelcomeEmailArgs) Kind() string { return "welcome_email" }6
7type WelcomeEmailWorker struct {8 river.WorkerDefaults[WelcomeEmailArgs]9 Reloop *reloop.Client10}11
12func (w *WelcomeEmailWorker) Work(ctx context.Context, job *river.Job[WelcomeEmailArgs]) error {13 _, err := w.Reloop.Mail.Send(reloop.SendMailParams{14 From: "Acme <hello@mail.acme.com>",15 To: job.Args.Email,16 Subject: "Welcome to Acme",17 Text: reloop.String("Thanks for signing up."),18 })19 if err != nil && !isRetryable(err) {20 return river.JobCancel(err) // 4xx: do not retry21 }22 return err // nil, or a retryable error River retries with backoff23}Register it with river.AddWorker(workers, &WelcomeEmailWorker{Reloop: client}). River retries returned errors with exponential backoff, up to 25 attempts by default. With asynq, return an error wrapping asynq.SkipRetry for the same effect as river.JobCancel.
Retries without duplicate emails
A request times out and your worker retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The Go SDK does not set this header, so call the endpoint with net/http. You can still reuse the SDK's types for the body, the response and the error:
1var httpClient = &http.Client{Timeout: 30 * time.Second}2
3func sendReceipt(ctx context.Context, orderID, to string) (*reloop.SendMailResponse, error) {4 body, err := json.Marshal(reloop.SendMailParams{5 From: "Acme <orders@mail.acme.com>",6 To: to,7 Subject: "Receipt for order " + orderID,8 Text: reloop.String("Thanks for your order."),9 })10 if err != nil {11 return nil, err12 }13
14 req, err := http.NewRequestWithContext(ctx, http.MethodPost,15 "https://reloop.sh/api/mail/v1/send", bytes.NewReader(body))16 if err != nil {17 return nil, err18 }19 req.Header.Set("x-api-key", os.Getenv("RELOOP_API_KEY"))20 req.Header.Set("Content-Type", "application/json")21 req.Header.Set("Idempotency-Key", "receipt-"+orderID)22
23 res, err := httpClient.Do(req)24 if err != nil {25 // Same shape as the SDK, so isRetryable works unchanged26 return nil, &reloop.APIError{Status: 0, StatusText: "Network Error",27 Body: reloop.APIErrorBody{Message: err.Error()}}28 }29 defer res.Body.Close()30
31 if res.StatusCode >= 400 {32 apiErr := &reloop.APIError{Status: res.StatusCode, StatusText: res.Status}33 _ = json.NewDecoder(res.Body).Decode(&apiErr.Body)34 return nil, apiErr35 }36
37 var out reloop.SendMailResponse38 if err := json.NewDecoder(res.Body).Decode(&out); err != nil {39 return nil, err40 }41 return &out, nil42}Base the key on the business event (receipt-{orderID}), not a new UUID per attempt, so retries from any worker are safe. If a request with the same key is still running, the API returns 409 with Retry-After: 1. Treat it like any other retryable error and try again with the same key. As a bonus, this version takes a context.Context, so it stops when the caller cancels.
Testing without sending real email
- Unit tests: point the SDK at an
httptest.ServerwithBaseURLand assert on the request body. No mocks or interfaces needed:
1func TestSendWelcome(t *testing.T) {2 var got map[string]any3 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {4 json.NewDecoder(r.Body).Decode(&got)5 w.Header().Set("Content-Type", "application/json")6 w.Write([]byte(`{"success":true,"id":"em_test"}`))7 }))8 defer srv.Close()9
10 client, _ := reloop.NewClient(reloop.ClientOptions{11 APIKey: "rl_test",12 BaseURL: srv.URL,13 })14
15 if err := SendWelcome(client, "ada@example.com"); err != nil {16 t.Fatal(err)17 }18 if got["to"] != "ada@example.com" {19 t.Errorf("to = %v", got["to"])20 }21}- Staging: send to test addresses so you do not hurt your sender reputation with bounces.
- Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpitand callsmtp.SendMail("localhost:1025", nil, ...)with no auth. Openhttp://localhost:8025to see the messages.
Production checklist
- API key in an environment variable or secrets manager
- Sending domain verified with SPF, DKIM and DMARC
-
Fromon your verified domain; user addresses inReplyTo - Both HTML and plain-text bodies
- One shared client, created at startup
- Sending in a worker (River, asynq, or a channel worker for low-stakes mail), not the request
- Retries only on network errors,
429and5xx - Idempotency keys on anything that retries
- Graceful shutdown that drains queued emails
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
With net/smtp, build a multipart/alternative body with mime/multipart: a text/plain part, then a text/html part, and set the Content-Type header with the boundary. With go-mail, call SetBodyString and AddAlternativeString. With the Reloop SDK, set the HTML and Text fields.
smtp.PlainAuth refuses to send credentials unless the connection uses TLS or the server is localhost. Connect on port 587 and let SendMail upgrade with STARTTLS. If the server does not offer STARTTLS, you get this error instead of leaking your password.
Not yet. Mail.Send uses an http.Client with a 30 second timeout, which you can replace with SetHTTPClient. If you need cancellation, call the HTTP API directly with http.NewRequestWithContext, as shown in the idempotency section.
Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.
A goroutine keeps the request fast, but it has no retries and is lost if the process exits. Use it for low-stakes mail. For anything that must arrive, use a persistent queue like River or asynq with retry rules and an idempotency key.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


