How to send an email with Go

Go, also known as Golang, is a modern programming language that excels in simplicity and efficiency. In this article, we will explore how to send emails using the net/smtp package, included in Go's standard library.

Prerequisites

Before you start, make sure you have:

  • A configured Go development environment.
  • Access to an SMTP server, such as Gmail or a similar provider.

Implementation

Below is an example code to send an email using Go:

package main

import (
    "fmt"
    "net/smtp"
)

func main() {
    // Email configuration
    from := "youremail@example.com"
    password := "yourpassword"
    to := []string{"recipient@example.com"}
    smtpHost := "smtp.example.com"
    smtpPort := "587"

    // Message body
    message := []byte("Subject: Test Email\r\n\r\nHi! This is an email sent from Go.")

    // Authentication
    auth := smtp.PlainAuth("", from, password, smtpHost)

    // Sending email
    err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, message)
    if err != nil {
        fmt.Println("Error while sending email:", err)
        return
    }

    fmt.Println("Email sent successfully!")
}

Code Explanation

The code above performs the following steps:

  1. Sets the variables for the email, including sender, recipient, SMTP server, and port.
  2. Composes the email message, including the Subject field.
  3. Uses the smtp.PlainAuth method for authentication.
  4. Sends the email with smtp.SendMail.

Make sure to replace the example values with the actual details of your email account and SMTP server.

Security Considerations

When handling sensitive credentials such as passwords, avoid hardcoding them in the code. Use environment variables or a credential management system for better security.

Conclusion

In this article, we demonstrated how to send an email using Go and the net/smtp package. This approach is simple and effective, but for more complex applications, you might consider third-party libraries like gomail.

Back to top