ntfy/server/mailer.go

44 lines
1.1 KiB
Go
Raw Normal View History

2021-12-24 12:03:04 +13:00
package server
import (
"fmt"
"net"
"net/smtp"
"strings"
)
type mailer interface {
2021-12-25 03:01:29 +13:00
Send(from, to string, m *message) error
2021-12-24 12:03:04 +13:00
}
type smtpMailer struct {
config *Config
}
2021-12-25 03:01:29 +13:00
func (s *smtpMailer) Send(from, to string, m *message) error {
2021-12-24 12:03:04 +13:00
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", " ")
2021-12-25 03:01:29 +13:00
message := m.Message
if len(m.Tags) > 0 {
message += "\nTags: " + strings.Join(m.Tags, ", ") // FIXME emojis
}
if m.Priority != 0 && m.Priority != 3 {
message += fmt.Sprintf("\nPriority: %d", m.Priority) // FIXME to string
}
message += fmt.Sprintf("\n\n--\nMessage was sent via %s by client %s", m.Topic, from) // FIXME short URL
2021-12-24 12:03:04 +13:00
msg := []byte(fmt.Sprintf("From: %s\r\n"+
"To: %s\r\n"+
"Subject: %s\r\n\r\n"+
2021-12-25 03:01:29 +13:00
"%s\r\n", s.config.SMTPFrom, to, subject, message))
2021-12-24 12:03:04 +13:00
auth := smtp.PlainAuth("", s.config.SMTPUser, s.config.SMTPPass, host)
return smtp.SendMail(s.config.SMTPAddr, auth, s.config.SMTPFrom, []string{to}, msg)
}