Sling Academy
Home/Golang/How to send emails using Go

How to send emails using Go

Last updated: November 27, 2024

Sending emails is a common requirement for many applications. In Go, sending emails can be accomplished using the net/smtp package, which provides a basic implementation of an SMTP client. In this article, we will walk you through the steps to send an email using Go.

Setting Up

To get started, you need to have Go installed on your system. If you haven't installed it yet, you can download it from the official Go website.

Basic Email Sending

Here is a simple example to demonstrate how to send an email using Go:

package main

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

func main() {
    // Set up authentication information.
    auth := smtp.PlainAuth("", "[email protected]", "your_password", "smtp.example.com")

    // Set up the email content.
    from := "[email protected]"
    to := []string{"[email protected]"}
    msg := []byte("To: [email protected]\r\n" +
        "Subject: Test Subject\r\n" +
        "\r\n" +
        "This is the email body.")

    // Send the email.
    err := smtp.SendMail("smtp.example.com:587", auth, from, to, msg)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Email sent successfully!")
}

In this example, replace [email protected], your_password, and smtp.example.com with your email address, password, and SMTP server address respectively. Similarly, change [email protected] with the recipient's email address.

Explanation

  • smtp.PlainAuth: This function is used to create authentication information for logging in to the SMTP server.
  • smtp.SendMail: This function sends the email by connecting to the SMTP server with the specified authentication.
  • msg: The email message format, which includes the recipient, subject, and the body.

Handling Errors

It's important to handle possible errors when sending emails. The log.Fatal() function will stop the program execution and log the error message if the email sending fails. You should replace this with more robust error handling in a production setting.

Using Third-Party Packages

The standard library covers basic email sending functionality, but you might need more features like sending HTML emails, attachments, or interfacing with email APIs. For these needs, consider using third-party packages such as gomail or dedicated email services with Go SDKs such as SendGrid, Mailgun, or AWS SES.

$ go get gopkg.in/gomail.v2

After installing gomail, here is how you can use it:

package main

import (
    "gopkg.in/gomail.v2"
)

func main() {
    m := gomail.NewMessage()
    m.SetHeader("From", "[email protected]")
    m.SetHeader("To", "[email protected]")
    m.SetHeader("Subject", "Test Subject")
    m.SetBody("text/html", "<h1>This is the email body</h1>")

    d := gomail.NewDialer("smtp.example.com", 587, "[email protected]", "your_password")

    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
    println("Email sent successfully!")
}

This code sends an HTML email using the gomail package.

Conclusion

Sending emails in Go can be straightforward using the net/smtp package, though there are limitations if you need more complex email features. Third-party libraries like gomail can help you overcome these limitations, providing more flexibility and ease of use.

Next Article: How to create a simple proxy server with Go

Previous Article: How to read and write PDF files using Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant