Improve mail service

This commit is contained in:
vinchent 2024-09-03 21:09:34 +02:00
parent a51282eeec
commit 31669da26d
8 changed files with 290 additions and 39 deletions

View File

@ -5,10 +5,8 @@ import (
"fmt"
"log"
"net/http"
"time"
"github.com/tsawler/toolbox"
mail "github.com/xhit/go-simple-mail/v2"
)
type MailData struct {
@ -35,7 +33,13 @@ func (app *Config) SendMail(w http.ResponseWriter, r *http.Request) {
return
}
err = app.SendMsg(mailData)
msg := Message{
From: mailData.From,
To: mailData.To,
Subject: mailData.Subject,
Data: mailData.Content,
}
err = app.Mailer.SendSMTPMessage(msg)
if err != nil {
log.Println(err)
app.Tools.ErrorJSON(w, err)
@ -48,37 +52,3 @@ func (app *Config) SendMail(w http.ResponseWriter, r *http.Request) {
app.Tools.WriteJSON(w, http.StatusAccepted, payload)
}
func (app *Config) SendMsg(m MailData) error {
server := mail.NewSMTPClient()
server.Host = app.Host
server.Port = app.Port
server.KeepAlive = false
server.ConnectTimeout = 10 * time.Second
server.SendTimeout = 10 * time.Second
smtpClient, err := server.Connect()
if err != nil {
log.Println(err)
return err
}
// Maybe add a template
email := mail.NewMSG()
email.SetFrom(m.From).
AddTo(m.To).
SetSubject(m.Subject).
SetBody(mail.TextHTML, m.Content)
err = email.Send(smtpClient)
if err != nil {
log.Println(err)
return err
}
log.Printf("Email sent to %s", m.To)
return nil
}

View File

@ -0,0 +1,168 @@
package main
import (
"bytes"
"embed"
"html/template"
"log"
"time"
"github.com/vanng822/go-premailer/premailer"
mail "github.com/xhit/go-simple-mail/v2"
)
//go:embed templates
var emailTemplateFS embed.FS
type Mail struct {
Domain string
Host string
Port int
Username string
Password string
Encryption string
FromAddr string
FromName string
}
type Message struct {
From string
FromName string
To string
Subject string
Attachments []string
Data any
DataMap map[string]any
}
func (m *Mail) SendSMTPMessage(msg Message) error {
if msg.From == "" {
msg.From = m.FromAddr
}
if msg.FromName == "" {
msg.FromName = m.FromName
}
data := map[string]any{
"message": msg.Data,
}
msg.DataMap = data
formattedMessage, err := m.buildHTMLMessage(msg)
if err != nil {
return err
}
plainMessage, err := m.buildPlainTextMessage(msg)
if err != nil {
return err
}
server := mail.NewSMTPClient()
server.Host = m.Host
server.Port = m.Port
server.Username = m.Username
server.Password = m.Password
server.Encryption = m.getEncryption(m.Encryption)
server.KeepAlive = false
server.ConnectTimeout = 10 * time.Second
server.SendTimeout = 10 * time.Second
log.Println(server.Host, server.Port)
smtpClient, err := server.Connect()
if err != nil {
return err
}
email := mail.NewMSG()
email.SetFrom(msg.From).AddTo(msg.To).SetSubject(msg.Subject)
email.SetBody(mail.TextPlain, plainMessage)
email.AddAlternative(mail.TextHTML, formattedMessage)
if len(msg.Attachments) > 0 {
for _, x := range msg.Attachments {
email.AddAttachment(x)
}
}
err = email.Send(smtpClient)
if err != nil {
return err
}
return nil
}
func (m *Mail) buildPlainTextMessage(msg Message) (string, error) {
templateToRender := "templates/mail.plain.gohtml"
t, err := template.New("email-plain").ParseFS(emailTemplateFS, templateToRender)
if err != nil {
return "", err
}
var tpl bytes.Buffer
if err = t.ExecuteTemplate(&tpl, "body", msg.DataMap); err != nil {
return "", err
}
formattedMessage := tpl.String()
return formattedMessage, nil
}
func (m *Mail) buildHTMLMessage(msg Message) (string, error) {
templateToRender := "templates/mail.html.gohtml"
t, err := template.New("email-html").ParseFS(emailTemplateFS, templateToRender)
if err != nil {
return "", err
}
var tpl bytes.Buffer
if err = t.ExecuteTemplate(&tpl, "body", msg.DataMap); err != nil {
return "", err
}
formattedMessage := tpl.String()
formattedMessage, err = m.inlineCSS(formattedMessage)
if err != nil {
return "", err
}
return formattedMessage, nil
}
func (m *Mail) inlineCSS(s string) (string, error) {
options := premailer.Options{
RemoveClasses: false,
CssToAttributes: false,
KeepBangImportant: true,
}
prem, err := premailer.NewPremailerFromString(s, &options)
if err != nil {
return "", err
}
html, err := prem.Transform()
if err != nil {
return "", err
}
return html, nil
}
func (m *Mail) getEncryption(s string) mail.Encryption {
switch s {
case "tls":
return mail.EncryptionSTARTTLS
case "ssl":
return mail.EncryptionSSLTLS
case "none":
return mail.EncryptionNone
default:
return mail.EncryptionNone
}
}

View File

@ -4,6 +4,8 @@ import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/tsawler/toolbox"
)
@ -17,12 +19,12 @@ type Config struct {
Password string
Encryption string
Tools toolbox.Tools
Mailer Mail
}
func main() {
app := Config{
Host: "mailhog",
Port: 1025,
Mailer: createMail(),
}
log.Printf("Starting mail service on port %s\n", webPort)
@ -38,3 +40,17 @@ func main() {
log.Panic(err)
}
}
func createMail() Mail {
port, _ := strconv.Atoi(os.Getenv("MAIL_PORT"))
return Mail{
Domain: os.Getenv("MAIL_DOMAIN"),
Host: os.Getenv("MAIL_HOST"),
Port: port,
Username: os.Getenv("MAIL_USERNAME"),
Password: os.Getenv("MAIL_PASSWORD"),
Encryption: os.Getenv("MAIL_ENCRYPTION"),
FromName: os.Getenv("FROM_NAME"),
FromAddr: os.Getenv("FROM_ADDR"),
}
}

View File

@ -0,0 +1,13 @@
{{ define "body" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<p>{{.message}}</p>
</body>
</html>
{{ end }}

View File

@ -0,0 +1,3 @@
{{ define "body" }}
{{.message}}
{{ end }}

View File

@ -6,11 +6,17 @@ require (
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/cors v1.2.1
github.com/tsawler/toolbox v1.3.1
github.com/vanng822/go-premailer v1.21.0
github.com/xhit/go-simple-mail/v2 v2.16.0
)
require (
github.com/PuerkitoBio/goquery v1.9.1 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/go-test/deep v1.1.1 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/toorop/go-dkim v0.0.0-20201103131630-e1cd1a0a5208 // indirect
github.com/vanng822/css v1.0.1 // indirect
golang.org/x/net v0.23.0 // indirect
)

View File

@ -1,20 +1,85 @@
github.com/PuerkitoBio/goquery v1.9.1 h1:mTL6XjbJTZdpfL+Gwl5U2h1l9yEkJjhmlTeV9VPW7UI=
github.com/PuerkitoBio/goquery v1.9.1/go.mod h1:cW1n6TmIMDoORQU5IU/P1T3tGFunOeXEpGP2WHRwkbY=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/toorop/go-dkim v0.0.0-20201103131630-e1cd1a0a5208 h1:PM5hJF7HVfNWmCjMdEfbuOBNXSVF2cMFGgQTPdKCbwM=
github.com/toorop/go-dkim v0.0.0-20201103131630-e1cd1a0a5208/go.mod h1:BzWtXXrXzZUvMacR0oF/fbDDgUPO8L36tDMmRAf14ns=
github.com/tsawler/toolbox v1.3.1 h1:zqnt5L5dmWiBrs2JgE1VeHJJO/IMStFKQgWxc+eriEE=
github.com/tsawler/toolbox v1.3.1/go.mod h1:bYUEtJ09HFx534XcjXdTIzv7MCKsg9SrhSGELFe6HI4=
github.com/unrolled/render v1.0.3/go.mod h1:gN9T0NhL4Bfbwu8ann7Ry/TGHYfosul+J0obPf6NBdM=
github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8=
github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w=
github.com/vanng822/go-premailer v1.21.0 h1:qIwX4urphNPO3xa60MGqowmyjzzMtFacJPKNrt1UWFU=
github.com/vanng822/go-premailer v1.21.0/go.mod h1:6Y3H2NzNmK3sFBNgR1ENdfV9hzG8hMzrA1nL/XBbbP4=
github.com/vanng822/r2router v0.0.0-20150523112421-1023140a4f30/go.mod h1:1BVq8p2jVr55Ost2PkZWDrG86PiJ/0lxqcXoAcGxvWU=
github.com/xhit/go-simple-mail/v2 v2.16.0 h1:ouGy/Ww4kuaqu2E2UrDw7SvLaziWTB60ICLkIkNVccA=
github.com/xhit/go-simple-mail/v2 v2.16.0/go.mod h1:b7P5ygho6SYE+VIqpxA6QkYfv4teeyG4MKqB3utRu98=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -39,6 +39,16 @@ services:
deploy:
mode: replicated
replicas: 1
environment:
MAIL_DOMAIN: localhost
MAIL_HOST: mailhog
MAIL_PORT: 1025
MAIL_USERNAME: ""
MAIL_PASSWORD: ""
MAIL_ENCRYPTION: none
FROM_NAME: me
FROM_ADDR: me@here.com
postgres:
image: postgres:16.4-alpine