package structs
import (
"bytes"
"html/template"
"net/smtp"
"strings"
"clickandjoin.app/emailserver/modules/cache"
"clickandjoin.app/emailserver/modules/config"
"github.com/sirupsen/logrus"
)
type Mail struct {
To []string
Subject string
TemplateId string
LanguageId string
BodyData interface{}
}
func (m *Mail) Send(body string) error {
cfg := config.Cfg.Mail
msg := "From: " + cfg.From + "\n" +
"To: " + strings.Join(m.To, ",") + "\n" +
"Subject: " + m.Subject + "\n" +
"MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" +
body
err := smtp.SendMail(cfg.Host+":"+cfg.Port, cache.SmtpAuth, cfg.From, m.To, []byte(msg))
if err != nil {
logrus.Warnln("smtp error:", err)
return err
}
logrus.Debugln("SEND MAIL", msg)
return nil
}
func (m *Mail) RenderTemplate() (string, error) {
body := cache.BodyTemplates[m.TemplateId]
for templateName, templateData := range cache.Templates.Templates {
// Skipping templates if the template ID is not the expected one
if templateName != m.TemplateId {
continue
}
logrus.Debugln("RENDER TEMPLATE", templateName, templateData)
m.Subject = templateData["mailSubject"][m.LanguageId]
// occurs if the requested language code does not exist
if m.Subject == "" {
m.Subject = templateData["mailSubject"][config.Cfg.DefaultLanguageCode]
}
// replace body %values% with values in templates config
for key, value := range templateData {
if key == "mailSubject" {
continue
}
v := value[m.LanguageId]
// occurs if the requested language code does not exist
if v == "" {
v = value[config.Cfg.DefaultLanguageCode]
}
body = []byte(strings.Replace(string(body), "%"+key+"%", v, -1))
}
}
t := template.Must(template.New("").Parse(string(body)))
buf := new(bytes.Buffer)
if err := t.Execute(buf, m.BodyData); err != nil {
return "", err
}
return buf.String(), nil
}