To send and receive email messages using SMTP and the net/smtp package in Go, you can follow these steps:
import (
"net/smtp"
"log"
)
smtpServer := "smtp.example.com" // Replace with your SMTP server address
smtpPort := "587" // Replace with the SMTP server port
email := "[email protected]" // Replace with your email address
password := "your-email-password" // Replace with your email password
from := "[email protected]" // Replace with your email address
to := "[email protected]" // Replace with the recipient's email address
subject := "Subject of the email"
message := "Body of the email"
msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s", from, to, subject, message)
auth := smtp.PlainAuth("", email, password, smtpServer)
client, err := smtp.Dial(smtpServer+":"+smtpPort)
if err != nil {
log.Fatal(err)
}
if err = client.Auth(auth); err != nil {
log.Fatal(err)
}
if err = client.Mail(email); err != nil {
log.Fatal(err)
}
if err = client.Rcpt(to); err != nil {
log.Fatal(err)
}
w, err := client.Data()
if err != nil {
log.Fatal(err)
}
_, err = w.Write([]byte(msg))
if err != nil {
log.Fatal(err)
}
err = w.Close()
if err != nil {
log.Fatal(err)
}
client.Quit()
These steps demonstrate how to send an email using SMTP and the net/smtp package in Go. If you want to receive an email, you can use the IMAP protocol and the net/mail package instead.