Email rate limiting + tests

This commit is contained in:
Philipp Heckel 2021-12-24 00:03:04 +01:00
parent 873c57b3d8
commit 7280ae1ebc
7 changed files with 183 additions and 34 deletions

35
server/mailer.go Normal file
View file

@ -0,0 +1,35 @@
package server
import (
"fmt"
"net"
"net/smtp"
"strings"
)
type mailer interface {
Send(to string, m *message) error
}
type smtpMailer struct {
config *Config
}
func (s *smtpMailer) Send(to string, m *message) error {
host, _, err := net.SplitHostPort(s.config.SMTPAddr)
if err != nil {
return err
}
subject := m.Title
if subject == "" {
subject = m.Message
}
subject += " - " + m.Topic
subject = strings.ReplaceAll(strings.ReplaceAll(subject, "\r", ""), "\n", " ")
msg := []byte(fmt.Sprintf("From: %s\r\n"+
"To: %s\r\n"+
"Subject: %s\r\n\r\n"+
"%s\r\n", s.config.SMTPFrom, to, subject, m.Message))
auth := smtp.PlainAuth("", s.config.SMTPUser, s.config.SMTPPass, host)
return smtp.SendMail(s.config.SMTPAddr, auth, s.config.SMTPFrom, []string{to}, msg)
}