65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/wneessen/go-mail"
|
|
ht "html/template"
|
|
)
|
|
|
|
// StmpConfig struct
|
|
type SmtpConfig struct {
|
|
Cfg *Config
|
|
}
|
|
|
|
func NewSmtpConfig(cfg *Config) *SmtpConfig {
|
|
smtpSetup := &SmtpConfig{
|
|
Cfg: cfg,
|
|
}
|
|
|
|
return smtpSetup
|
|
}
|
|
|
|
func (_smtp *SmtpConfig) SendEmail(subject string, toAddress string, toName string, htmlBody string) (err error) {
|
|
println(_smtp.Cfg.Smtp.Host)
|
|
println(_smtp.Cfg.Smtp.Port)
|
|
println(_smtp.Cfg.Smtp.Username)
|
|
println(_smtp.Cfg.Smtp.Password)
|
|
println(subject)
|
|
println(toAddress)
|
|
println(toName)
|
|
println(htmlBody)
|
|
|
|
client, err := mail.NewClient(_smtp.Cfg.Smtp.Host, mail.WithPort(_smtp.Cfg.Smtp.Port), mail.WithSSL(),
|
|
mail.WithSMTPAuth(mail.SMTPAuthPlain), mail.WithUsername(_smtp.Cfg.Smtp.Username), mail.WithPassword(_smtp.Cfg.Smtp.Password))
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create mail client: %s\n", err)
|
|
}
|
|
|
|
message := mail.NewMsg()
|
|
|
|
if err := message.EnvelopeFrom(_smtp.Cfg.Smtp.FromAddress); err != nil {
|
|
return fmt.Errorf("failed to set ENVELOPE FROM address: %s", err)
|
|
}
|
|
if err := message.FromFormat(_smtp.Cfg.Smtp.FromName, _smtp.Cfg.Smtp.FromAddress); err != nil {
|
|
return fmt.Errorf("failed to set formatted FROM address: %s", err)
|
|
}
|
|
if err := message.AddToFormat(toName, toAddress); err != nil {
|
|
return fmt.Errorf("failed to set formatted TO address: %s", err)
|
|
}
|
|
|
|
message.SetMessageID()
|
|
message.SetDate()
|
|
message.Subject(subject)
|
|
|
|
htmlTpl, err := ht.New("htmltpl").Parse(htmlBody)
|
|
if err := message.SetBodyHTMLTemplate(htmlTpl, toAddress); err != nil {
|
|
return fmt.Errorf("failed to add HTML template to mail body: %s", err)
|
|
}
|
|
|
|
if err = client.DialAndSend(message); err != nil {
|
|
return fmt.Errorf("failed to send mail: %s\n", err)
|
|
}
|
|
|
|
return nil
|
|
}
|