How to Send Emails from Go

Web
Send emails in Go using the net/smtp package with a simple SMTP client and plain text message construction.

Use the net/smtp package to send emails via SMTP. Create a message with mail and mime/multipart, then dial the server and send it.

package main

import (
	"bytes"
	"fmt"
	"net/smtp"
	"net/textproto"
)

func main() {
	from := "sender@example.com"
	password := "your-password"
	to := []string{"recipient@example.com"}
	subject := "Test Subject"
	body := "Hello, this is a test email."

	msg := &bytes.Buffer{}
	msg.WriteString(fmt.Sprintf("To: %s\r\n", to[0]))
	msg.WriteString(fmt.Sprintf("From: %s\r\n", from))
	msg.WriteString(fmt.Sprintf("Subject: %s\r\n", subject))
	msg.WriteString(fmt.Sprintf("MIME-Version: 1.0\r\n"))
	msg.WriteString(fmt.Sprintf("Content-Type: text/plain; charset=UTF-8\r\n"))
	msg.WriteString("\r\n")
	msg.WriteString(body)

	auth := smtp.PlainAuth("", from, password, "smtp.example.com")
	err := smtp.SendMail("smtp.example.com:587", auth, from, to, msg.Bytes())
	if err != nil {
		panic(err)
	}
	fmt.Println("Email sent!")
}