2024-08-19 22:37:30 +01:00
|
|
|
package mail
|
|
|
|
|
|
|
|
import (
|
2024-10-05 21:08:02 +01:00
|
|
|
"embed"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"github.com/1f349/overlapfs"
|
|
|
|
"github.com/1f349/simplemail"
|
2024-08-19 22:37:30 +01:00
|
|
|
"github.com/emersion/go-message/mail"
|
2024-10-05 21:08:02 +01:00
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2024-08-19 22:37:30 +01:00
|
|
|
)
|
|
|
|
|
2024-10-05 21:08:02 +01:00
|
|
|
//go:embed templates/*.go.html templates/*.go.txt
|
|
|
|
var embeddedTemplates embed.FS
|
2024-08-19 22:37:30 +01:00
|
|
|
|
2024-10-05 21:08:02 +01:00
|
|
|
type Mail struct {
|
|
|
|
mail *simplemail.SimpleMail
|
|
|
|
name string
|
2024-08-19 22:37:30 +01:00
|
|
|
}
|
|
|
|
|
2024-10-05 21:08:02 +01:00
|
|
|
func New(sender *simplemail.Mail, wd, name string) (*Mail, error) {
|
|
|
|
var o fs.FS = embeddedTemplates
|
|
|
|
o, _ = fs.Sub(o, "templates")
|
|
|
|
if wd != "" {
|
|
|
|
mailDir := filepath.Join(wd, "mail-templates")
|
|
|
|
err := os.Mkdir(mailDir, os.ModePerm)
|
|
|
|
if err == nil || errors.Is(err, os.ErrExist) {
|
|
|
|
wdFs := os.DirFS(mailDir)
|
|
|
|
o = overlapfs.OverlapFS{A: embeddedTemplates, B: wdFs}
|
2024-08-19 22:37:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-05 21:08:02 +01:00
|
|
|
simpleMail, err := simplemail.New(sender, o)
|
|
|
|
return &Mail{
|
|
|
|
mail: simpleMail,
|
|
|
|
name: name,
|
|
|
|
}, err
|
|
|
|
}
|
2024-08-19 22:37:30 +01:00
|
|
|
|
2024-10-05 21:08:02 +01:00
|
|
|
func (m *Mail) SendEmailTemplate(templateName, subject, nameOfUser string, to *mail.Address, data map[string]any) error {
|
|
|
|
return m.mail.Send(templateName, fmt.Sprintf("%s - %s", subject, m.name), to, map[string]any{
|
|
|
|
"ServiceName": m.name,
|
|
|
|
"Name": nameOfUser,
|
|
|
|
"Data": data,
|
|
|
|
})
|
2024-08-19 22:37:30 +01:00
|
|
|
}
|