gomail: Sending email in Go
gomail is a powerful and easy-to-use library for sending emails in the Go (Golang) programming language. It provides a convenient interface for creating and sending emails with support for attachments, HTML templates, multiple recipients, and SMTP authentication. The library is actively maintained by the community and is one of the standard solutions for working with email in the Go ecosystem.
Why use gomail?
Sending email is a common task in web applications: user registration, password reset, notifications, newsletters. The standard Go library (net/smtp) provides basic capabilities but requires a lot of manual work: encoding attachments, forming MIME headers, working with HTML templates. gomail handles all these complexities, allowing you to focus on your application logic.
Installation
Installation is done using the standard go get command:
go get gopkg.in/gomail.v2To use it in your project, import the package:
import "gopkg.in/gomail.v2"Main features
- Simple sending: minimal code to send an email with text or HTML.
- Attachment support: you can attach files (images, PDFs, documents).
- Multiple recipients: To, Cc, Bcc.
- HTML and text: support for multipart/alternative emails.
- Authentication: support for LOGIN, PLAIN, CRAM-MD5.
- Custom headers: ability to add your own headers (Reply-To, Message-ID, etc.).
- Mailing groups: convenient for mass mailings.
Code example in Go (Golang)
Below is a complete example of sending an email with HTML content and an attachment via a Gmail SMTP server:
package main
import ( "gopkg.in/gomail.v2" "log")
func main() { m := gomail.NewMessage() m.SetHeader("From", "youremail@gmail.com") m.SetHeader("To", "recipient@example.com") m.SetHeader("Subject", "Hello from Go!") m.SetBody("text/html", "<h1>Hello!</h1><p>This is a test email.</p>") m.Attach("/path/to/file.pdf")
d := gomail.NewDialer("smtp.gmail.com", 587, "youremail@gmail.com", "yourpassword")
if err := d.DialAndSend(m); err != nil { log.Fatal(err) } log.Println("Email sent successfully")}When to use gomail?
- When you need reliable email sending with attachments and HTML formatting.
- When building server-side applications in Go that require integration with email notifications.
- For mass mailings (using a connection pool).
- If you are tired of manually encoding MIME and want clean, readable code.
The gomail library is an excellent choice for any Go project that requires email sending. It is simple, documented, and covered by tests.
Also in library
Working with Images in TypeScript: Libraries, Tools, and Code Examples
Geolocation and Maps in Java: Libraries, API and Code Examples
Working with ZIP Archives in Kotlin: Creation, Reading, and Extraction
Sending SMS in Kotlin: smslib4k API Library