103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package internal
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"text/template"
|
|
|
|
"github.com/go-mail/mail"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var (
|
|
ErrSendingEmail = errors.New("error: unable to send email")
|
|
|
|
supportRequestEmailTemplate = template.Must(template.New("email").Parse(`Hello,
|
|
|
|
{{ .Name }} <{{ .Email }} from {{ .Instance }} has sent the following support request:
|
|
|
|
> Subject: {{ .Subject }}
|
|
>
|
|
{{ .Message }}
|
|
|
|
Kind regards,
|
|
|
|
{{ .Instance }} Support
|
|
`))
|
|
)
|
|
|
|
type SupportRequestEmailContext struct {
|
|
Instance string
|
|
|
|
Name string
|
|
Email string
|
|
Subject string
|
|
Message string
|
|
}
|
|
|
|
// indents a block of text with an indent string
|
|
func Indent(text, indent string) string {
|
|
if text[len(text)-1:] == "\n" {
|
|
result := ""
|
|
for _, j := range strings.Split(text[:len(text)-1], "\n") {
|
|
result += indent + j + "\n"
|
|
}
|
|
return result
|
|
}
|
|
result := ""
|
|
for _, j := range strings.Split(strings.TrimRight(text, "\n"), "\n") {
|
|
result += indent + j + "\n"
|
|
}
|
|
return result[:len(result)-1]
|
|
}
|
|
|
|
func SendEmail(conf *Config, recipients []string, replyTo, subject string, body string) error {
|
|
m := mail.NewMessage()
|
|
m.SetHeader("From", conf.SMTPFrom)
|
|
m.SetHeader("To", recipients...)
|
|
m.SetHeader("Reply-To", replyTo)
|
|
m.SetHeader("Subject", subject)
|
|
m.SetBody("text/plain", body)
|
|
|
|
d := mail.NewDialer(conf.SMTPHost, conf.SMTPPort, conf.SMTPUser, conf.SMTPPass)
|
|
|
|
err := d.DialAndSend(m)
|
|
if err != nil {
|
|
log.WithError(err).Error("SendEmail() failed")
|
|
return ErrSendingEmail
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func SendSupportRequestEmail(conf *Config, name, email, subject, message string) error {
|
|
recipients := []string{conf.AdminEmail, email}
|
|
emailSubject := fmt.Sprintf(
|
|
"[%s Support Request]: %s",
|
|
conf.Name, subject,
|
|
)
|
|
ctx := SupportRequestEmailContext{
|
|
Instance: conf.Name,
|
|
|
|
Name: name,
|
|
Email: email,
|
|
Subject: subject,
|
|
Message: Indent(message, "> "),
|
|
}
|
|
|
|
buf := &bytes.Buffer{}
|
|
if err := supportRequestEmailTemplate.Execute(buf, ctx); err != nil {
|
|
log.WithError(err).Error("error rendering email template")
|
|
return err
|
|
}
|
|
|
|
if err := SendEmail(conf, recipients, email, emailSubject, buf.String()); err != nil {
|
|
log.WithError(err).Errorf("error sending support request to %s", recipients[0])
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|