udemy-go-web-1/cmd/web/send-mail.go

59 lines
1.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"fmt"
"go-udemy-web-1/internal/models"
"log"
"os"
"strings"
"time"
mail "github.com/xhit/go-simple-mail"
)
func listenForMail() {
go func() {
for {
msg := <-app.MailChan
sendMsg(msg)
}
}()
}
func sendMsg(m models.MailData) {
server := mail.NewSMTPClient()
server.Host = "localhost"
server.Port = 1025 // fake port
server.KeepAlive = false
server.ConnectTimeout = 10 * time.Second
server.SendTimeout = 10 * time.Second
client, err := server.Connect()
if err != nil {
errorLog.Println(err)
}
email := mail.NewMSG()
email.SetFrom(m.From).AddTo(m.To).SetSubject(m.Subject)
if m.Template == "" {
email.SetBody(mail.TextHTML, m.Content)
} else {
data, err := os.ReadFile(fmt.Sprintf("./email-templates/%s", m.Template))
if err != nil {
app.ErrorLog.Println(err)
email.SetBody(mail.TextHTML, m.Content)
} else {
mailTemplate := string(data)
msgToSend := strings.Replace(mailTemplate, "[%body%]", m.Content, 1)
email.SetBody(mail.TextHTML, msgToSend)
}
}
err = email.Send(client)
if err != nil {
log.Println(err)
} else {
log.Println("Email sent")
}
}