76 lines
1.6 KiB
Go
76 lines
1.6 KiB
Go
package email
|
|
|
|
import (
|
|
"bytes"
|
|
"text/template"
|
|
"time"
|
|
|
|
"code.chrissexton.org/cws/happy/user"
|
|
|
|
mail "github.com/xhit/go-simple-mail"
|
|
)
|
|
|
|
var NoReply = `noreply@chrissexton.org`
|
|
var NewUserSubject = `Welcome to Happy`
|
|
var NewUserBody = `Welcome, {{.String}},
|
|
|
|
You may activate your new account with this link:
|
|
{{.BaseURL}}/user/{{.String}}/{{.Verification}}
|
|
|
|
Be sure to keep this URL and use it to log in to any devices. If you should lose it, just ask for a new one via the website.
|
|
You should always see {{.String}} at the bottom of the screen if you are logged in to this account.`
|
|
|
|
var newUserTpl = template.Must(template.New("NewUser").Parse(NewUserBody))
|
|
|
|
type EMailClient struct {
|
|
*mail.SMTPServer
|
|
}
|
|
|
|
func New(addr string, port int, user, pass string) *EMailClient {
|
|
m := EMailClient{
|
|
mail.NewSMTPClient(),
|
|
}
|
|
m.Host = addr
|
|
m.Port = port
|
|
m.Username = user
|
|
m.Password = pass
|
|
m.Encryption = mail.EncryptionTLS
|
|
|
|
m.KeepAlive = false
|
|
m.ConnectTimeout = 10 * time.Second
|
|
m.SendTimeout = 10 * time.Second
|
|
|
|
return &m
|
|
}
|
|
|
|
func (e *EMailClient) Send(from, to, subject, body string, isHTML bool) error {
|
|
client, err := e.Connect()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
msg := mail.NewMSG()
|
|
|
|
if isHTML {
|
|
msg.SetBody(mail.TextHTML, body)
|
|
} else {
|
|
msg.SetBody(mail.TextPlain, body)
|
|
}
|
|
|
|
msg.SetFrom(from).
|
|
AddTo(to).
|
|
SetSubject(subject)
|
|
|
|
err = msg.Send(client)
|
|
return err
|
|
}
|
|
|
|
func (e *EMailClient) SendNewUserMail(to string, u user.User, url string) error {
|
|
w := bytes.NewBufferString("")
|
|
tplArgs := struct {
|
|
user.User
|
|
BaseURL string
|
|
}{u, url}
|
|
newUserTpl.Execute(w, tplArgs)
|
|
return e.Send(NoReply, to, NewUserSubject, w.String(), false)
|
|
}
|