Sending email in Go (Golang): overview of libraries and tools
Go (Golang) is a modern compiled language that is excellent for building backend services, microservices, and automation. One common task is programmatically sending emails. In this article, we will thoroughly examine Go's standard tools for working with SMTP, popular third-party libraries, as well as examples of sending plain text and HTML emails with attachments.
Standard package net/smtp
The Go standard library includes the net/smtp package, which provides basic capabilities for sending email via an SMTP server. It is simple but requires manual construction of the email body (including headers, MIME types).
Simple example of sending a text email
package main
import ( "fmt" "net/smtp")
func main() { // Authentication data from := "your_email@gmail.com" password := "your_app_password" to := []string{"recipient@example.com"}
// SMTP server (e.g., Gmail) smtpHost := "smtp.gmail.com" smtpPort := "587"
// Email body (must include headers) subject := "Subject: Hello from Go!" body := "This is a test email sent using net/smtp." message := []byte(subject + "" + body)
// Authentication auth := smtp.PlainAuth("", from, password, smtpHost)
// Sending err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, message) if err != nil { fmt.Println("Error sending:", err) return } fmt.Println("Email sent successfully!")}Important: For Gmail, you will need an app password, not your regular password.
Sending HTML emails and emails with attachments
The net/smtp package cannot automatically form MIME messages. For HTML emails or attachments, you will have to manually compose the Content-Type headers and encode attachments in base64. This is cumbersome, so for complex emails it is better to use third-party libraries.
Popular third-party libraries for sending email in Go
There are several mature libraries that significantly simplify the work:
- go-gomail/gomail — one of the most popular. Supports HTML, attachments, image embedding, multiple recipients.
- jordan-wright/email — a lightweight library with a convenient API.
- sendgrid/sendgrid-go — the official client for the SendGrid service (suitable for mass mailings).
Example with go-gomail
package main
import ( "fmt" "gopkg.in/gomail.v2")
func main() { m := gomail.NewMessage() m.SetHeader("From", "your_email@gmail.com") m.SetHeader("To", "recipient@example.com") m.SetHeader("Subject", "HTML email with attachment") m.SetBody("text/html", "<h1>Hello!</h1><p>This is an <b>HTML</b> email.</p>") m.Attach("/path/to/file.pdf") // Attachment
d := gomail.NewDialer("smtp.gmail.com", 587, "your_email@gmail.com", "your_app_password")
if err := d.DialAndSend(m); err != nil { fmt.Println("Error:", err) return } fmt.Println("Email sent!")}Asynchronous sending and connection pooling
If you need to send many emails (for example, after user registration), it is important not to block the main thread. Go handles concurrency excellently: