smtp_sender.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package server
  2. import (
  3. _ "embed" // required by go:embed
  4. "encoding/json"
  5. "fmt"
  6. "heckel.io/ntfy/log"
  7. "heckel.io/ntfy/util"
  8. "mime"
  9. "net"
  10. "net/smtp"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. type mailer interface {
  16. Send(v *visitor, m *message, to string) error
  17. Counts() (total int64, success int64, failure int64)
  18. }
  19. type smtpSender struct {
  20. config *Config
  21. success int64
  22. failure int64
  23. mu sync.Mutex
  24. }
  25. func (s *smtpSender) Send(v *visitor, m *message, to string) error {
  26. return s.withCount(v, m, func() error {
  27. host, _, err := net.SplitHostPort(s.config.SMTPSenderAddr)
  28. if err != nil {
  29. return err
  30. }
  31. message, err := formatMail(s.config.BaseURL, v.ip, s.config.SMTPSenderFrom, to, m)
  32. if err != nil {
  33. return err
  34. }
  35. auth := smtp.PlainAuth("", s.config.SMTPSenderUser, s.config.SMTPSenderPass, host)
  36. log.Debug("%s Sending mail: via=%s, user=%s, pass=***, to=%s", logMessagePrefix(v, m), s.config.SMTPSenderAddr, s.config.SMTPSenderUser, to)
  37. log.Trace("%s Mail body: %s", logMessagePrefix(v, m), message)
  38. return smtp.SendMail(s.config.SMTPSenderAddr, auth, s.config.SMTPSenderFrom, []string{to}, []byte(message))
  39. })
  40. }
  41. func (s *smtpSender) Counts() (total int64, success int64, failure int64) {
  42. s.mu.Lock()
  43. defer s.mu.Unlock()
  44. return s.success + s.failure, s.success, s.failure
  45. }
  46. func (s *smtpSender) withCount(v *visitor, m *message, fn func() error) error {
  47. err := fn()
  48. s.mu.Lock()
  49. defer s.mu.Unlock()
  50. if err != nil {
  51. log.Debug("%s Sending mail failed: %s", logMessagePrefix(v, m), err.Error())
  52. s.failure++
  53. } else {
  54. s.success++
  55. }
  56. return err
  57. }
  58. func formatMail(baseURL, senderIP, from, to string, m *message) (string, error) {
  59. topicURL := baseURL + "/" + m.Topic
  60. subject := m.Title
  61. if subject == "" {
  62. subject = m.Message
  63. }
  64. subject = strings.ReplaceAll(strings.ReplaceAll(subject, "\r", ""), "\n", " ")
  65. message := m.Message
  66. trailer := ""
  67. if len(m.Tags) > 0 {
  68. emojis, tags, err := toEmojis(m.Tags)
  69. if err != nil {
  70. return "", err
  71. }
  72. if len(emojis) > 0 {
  73. subject = strings.Join(emojis, " ") + " " + subject
  74. }
  75. if len(tags) > 0 {
  76. trailer = "Tags: " + strings.Join(tags, ", ")
  77. }
  78. }
  79. if m.Priority != 0 && m.Priority != 3 {
  80. priority, err := util.PriorityString(m.Priority)
  81. if err != nil {
  82. return "", err
  83. }
  84. if trailer != "" {
  85. trailer += "\n"
  86. }
  87. trailer += fmt.Sprintf("Priority: %s", priority)
  88. }
  89. if trailer != "" {
  90. message += "\n\n" + trailer
  91. }
  92. subject = mime.BEncoding.Encode("utf-8", subject)
  93. body := `From: "{shortTopicURL}" <{from}>
  94. To: {to}
  95. Subject: {subject}
  96. Content-Type: text/plain; charset="utf-8"
  97. {message}
  98. --
  99. This message was sent by {ip} at {time} via {topicURL}`
  100. body = strings.ReplaceAll(body, "{from}", from)
  101. body = strings.ReplaceAll(body, "{to}", to)
  102. body = strings.ReplaceAll(body, "{subject}", subject)
  103. body = strings.ReplaceAll(body, "{message}", message)
  104. body = strings.ReplaceAll(body, "{topicURL}", topicURL)
  105. body = strings.ReplaceAll(body, "{shortTopicURL}", util.ShortTopicURL(topicURL))
  106. body = strings.ReplaceAll(body, "{time}", time.Unix(m.Time, 0).UTC().Format(time.RFC1123))
  107. body = strings.ReplaceAll(body, "{ip}", senderIP)
  108. return body, nil
  109. }
  110. var (
  111. //go:embed "mailer_emoji.json"
  112. emojisJSON string
  113. )
  114. type emoji struct {
  115. Emoji string `json:"emoji"`
  116. Aliases []string `json:"aliases"`
  117. }
  118. func toEmojis(tags []string) (emojisOut []string, tagsOut []string, err error) {
  119. var emojis []emoji
  120. if err = json.Unmarshal([]byte(emojisJSON), &emojis); err != nil {
  121. return nil, nil, err
  122. }
  123. tagsOut = make([]string, 0)
  124. emojisOut = make([]string, 0)
  125. nextTag:
  126. for _, t := range tags { // TODO Super inefficient; we should just create a .json file with a map
  127. for _, e := range emojis {
  128. if util.Contains(e.Aliases, t) {
  129. emojisOut = append(emojisOut, e.Emoji)
  130. continue nextTag
  131. }
  132. }
  133. tagsOut = append(tagsOut, t)
  134. }
  135. return
  136. }