To create and send MIME-encoded email messages in Go, you can make use of the built-in net/smtp
package along with the github.com/jordan-wright/email
package.
Here's an example code snippet that demonstrates how to create and send a MIME-encoded email in Go:
package main
import (
"log"
"net/smtp"
"github.com/jordan-wright/email"
)
func main() {
// Create a new email message
m := email.NewEmail()
// Set the sender and recipient
m.From = "[email protected]"
m.To = []string{"[email protected]"}
// Set the subject
m.Subject = "Hello, MIME!"
// Set the email body as MIME-encoded HTML content
m.HTML = []byte(`
<html>
<body>
<h1>Email Content</h1>
<p>This is a <strong>MIME-encoded</strong> email.</p>
</body>
</html>
`)
// Attach a file if needed
err := m.AttachFile("path/to/file.txt")
if err != nil {
log.Fatal(err)
}
// Connect to the SMTP server
smtpAddr := "smtp.example.com:587"
auth := smtp.PlainAuth("", "username", "password", "smtp.example.com")
err = m.Send(smtpAddr, auth)
if err != nil {
log.Fatal(err)
}
log.Println("Email sent successfully!")
}
Make sure to replace the placeholder values with your actual email addresses, SMTP server details, and authentication credentials.
To run this code, you need to have the github.com/jordan-wright/email
package installed. You can install it using the following command:
go get github.com/jordan-wright/email
Once installed, you can run your Go program using the go run
command:
go run filename.go
This should create and send a MIME-encoded email with an HTML content and an optional attachment.