How to send and receive email messages using SMTP and the net/smtp package in Go?

To send and receive email messages using SMTP and the net/smtp package in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "net/smtp" "log" )
  1. Set the SMTP server details:
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
  1. Create the email message:
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)
  1. Connect to the SMTP server:
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) }
  1. Send the email:
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) }
  1. Close the connection:
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.