gomailer/pkg/mail.go

113 lines
2.2 KiB
Go
Raw Normal View History

2023-04-08 00:31:59 +00:00
package gomailer
import (
"crypto/tls"
"github.com/wneessen/go-mail"
ht "html/template"
"log"
)
type MailSettings struct {
Subject string
From string
To string
Cc string
Inline bool
Template string
}
type MailServer struct {
Port int
Host string
Username string
Password string
Tls string
Authtype string
Skipverify bool
}
func SendMail(mailsettings MailSettings, serversettings MailServer) {
html := LoadTemplate(mailsettings.Template, true)
m := mail.NewMsg()
if err := m.From(mailsettings.From); err != nil {
log.Fatalf("failed to set From address: %s", err)
}
if err := m.To(mailsettings.From); err != nil {
log.Fatalf("failed to set To address: %s", err)
}
m.Subject(mailsettings.Subject)
htpl, err := ht.New("htmltpl").Parse(html)
if err != nil {
log.Fatalf("failed to parse text template: %s", err)
}
// embedd images
for _, val := range FindSrcInHtml(html) {
log.Println("Embedding: " + val)
m.EmbedFile(val)
}
// set template
m.SetBodyHTMLTemplate(htpl, nil)
// generate client
c, err := getClient(serversettings)
if err != nil {
log.Fatalf("failed to create mail client: %s", err)
}
// send mail
if err := c.DialAndSend(m); err != nil {
log.Fatalf("failed to send mail: %s", err)
}
}
func getClient(config MailServer) (*mail.Client, error) {
var authType mail.SMTPAuthType
switch config.Authtype {
case "plain":
authType = mail.SMTPAuthPlain
case "login":
authType = mail.SMTPAuthLogin
case "cram-md5":
authType = mail.SMTPAuthCramMD5
}
// tlsPolicy := mail.TLSOpportunistic
tlsPolicy := mail.DefaultTLSPolicy
switch config.Tls {
case "notls":
tlsPolicy = mail.NoTLS
case "mandatory":
tlsPolicy = mail.TLSMandatory
}
opts := []mail.Option{
mail.WithPort(config.Port),
mail.WithTLSPolicy(tlsPolicy),
mail.WithTLSConfig(&tls.Config{
InsecureSkipVerify: config.Skipverify,
}),
}
if config.Authtype != "nologin" {
opts = append(opts, mail.WithSMTPAuth(authType))
}
if config.Username != "" {
opts = append(opts, mail.WithUsername(config.Username))
}
if config.Password != "" {
opts = append(opts, mail.WithPassword(config.Password))
}
return mail.NewClient(
config.Host,
opts...,
)
}