2024-07-16 11:55:35 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-07-17 20:34:03 +00:00
|
|
|
"fmt"
|
2024-07-16 11:55:35 +00:00
|
|
|
"go-udemy-web-1/internal/models"
|
|
|
|
"log"
|
2024-07-17 20:34:03 +00:00
|
|
|
"os"
|
|
|
|
"strings"
|
2024-07-16 11:55:35 +00:00
|
|
|
"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)
|
2024-07-17 20:34:03 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2024-07-16 11:55:35 +00:00
|
|
|
|
|
|
|
err = email.Send(client)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
} else {
|
|
|
|
log.Println("Email sent")
|
|
|
|
}
|
|
|
|
}
|