Sending Emails in Go: A Comprehensive Guide
Using the smtp Package
The smtp
package is part of the Go standard library, making it easy to get started. To use it, you’ll need to import the following packages:
import (
"crypto/tls"
"fmt"
"log"
"net/smtp"
)
Next, declare variables for the email’s content:
var (
from = "[email protected]"
password = "your-password"
to = "[email protected]"
host = "smtp.gmail.com"
port = 587
subject = "Test Email"
body = "This is a test email sent using Go."
)
Create a map to combine the email’s data:
headerMap := map[string]string{
"From": from,
"To": to,
"Subject": subject,
}
Use the PlainAuth
method to authenticate the email:
auth := smtp.PlainAuth("", from, password, host)
Set up the TLS configuration and dial a connection:
tlsConfig := &tls.Config{ServerName: host}
conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", host, port), tlsConfig)
if err!= nil {
log.Fatal(err)
}
Create a client instance and authenticate:
client, err := smtp.NewClient(conn, host)
if err!= nil {
log.Fatal(err)
}
if err := client.Auth(auth); err!= nil {
log.Fatal(err)
}
Finally, write the email to the client and close the connection:
writer, err := client.Data()
if err!= nil {
log.Fatal(err)
}
_, err = writer.Write([]byte(body))
if err!= nil {
log.Fatal(err)
}
err = writer.Close()
if err!= nil {
log.Fatal(err)
}
err = client.Quit()
if err!= nil {
log.Fatal(err)
}
Using the email Package
The email
package is a third-party library that provides a simpler way to send emails. To use it, install the package using the following command:
go get github.com/jordan-wright/email
Import the package:
import (
"github.com/jordan-wright/email"
"fmt"
"log"
)
Declare variables for the email’s content:
var (
from = "[email protected]"
password = "your-password"
to = "[email protected]"
host = "smtp.gmail.com"
port = 587
subject = "Test Email"
body = "This is a test email sent using Go."
)
Create an email instance:
e := email.NewEmail()
e.From = from
e.To = []string{to}
e.Subject = subject
e.Text = []byte(body)
Send the email:
err := e.Send(fmt.Sprintf("%s:%d", host, port), smtp.PlainAuth("", from, password, host))
if err!= nil {
log.Fatal(err)
}
Comparison
Package | Pros | Cons |
---|---|---|
smtp | Built-in, customizable | Complex, requires manual authentication |
Simple, easy to use | Third-party dependency, less customizable |
Choose the smtp
package if you need more control over the email sending process or want to avoid third-party dependencies. Choose the email
package if you want a simple and easy-to-use solution for sending emails.