smtp_sender.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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.String(), 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. ev := logvm(v, m).
  37. Tag(tagEmail).
  38. Fields(log.Context{
  39. "email_via": s.config.SMTPSenderAddr,
  40. "email_user": s.config.SMTPSenderUser,
  41. "email_to": to,
  42. })
  43. if ev.IsTrace() {
  44. ev.Field("email_body", message).Trace("Sending email")
  45. } else if ev.IsDebug() {
  46. ev.Debug("Sending email")
  47. }
  48. return smtp.SendMail(s.config.SMTPSenderAddr, auth, s.config.SMTPSenderFrom, []string{to}, []byte(message))
  49. })
  50. }
  51. func (s *smtpSender) Counts() (total int64, success int64, failure int64) {
  52. s.mu.Lock()
  53. defer s.mu.Unlock()
  54. return s.success + s.failure, s.success, s.failure
  55. }
  56. func (s *smtpSender) withCount(v *visitor, m *message, fn func() error) error {
  57. err := fn()
  58. s.mu.Lock()
  59. defer s.mu.Unlock()
  60. if err != nil {
  61. logvm(v, m).Err(err).Debug("Sending mail failed")
  62. s.failure++
  63. } else {
  64. s.success++
  65. }
  66. return err
  67. }
  68. func formatMail(baseURL, senderIP, from, to string, m *message) (string, error) {
  69. topicURL := baseURL + "/" + m.Topic
  70. subject := m.Title
  71. if subject == "" {
  72. subject = m.Message
  73. }
  74. subject = strings.ReplaceAll(strings.ReplaceAll(subject, "\r", ""), "\n", " ")
  75. message := m.Message
  76. trailer := ""
  77. if len(m.Tags) > 0 {
  78. emojis, tags, err := toEmojis(m.Tags)
  79. if err != nil {
  80. return "", err
  81. }
  82. if len(emojis) > 0 {
  83. subject = strings.Join(emojis, " ") + " " + subject
  84. }
  85. if len(tags) > 0 {
  86. trailer = "Tags: " + strings.Join(tags, ", ")
  87. }
  88. }
  89. if m.Priority != 0 && m.Priority != 3 {
  90. priority, err := util.PriorityString(m.Priority)
  91. if err != nil {
  92. return "", err
  93. }
  94. if trailer != "" {
  95. trailer += "\n"
  96. }
  97. trailer += fmt.Sprintf("Priority: %s", priority)
  98. }
  99. if trailer != "" {
  100. message += "\n\n" + trailer
  101. }
  102. subject = mime.BEncoding.Encode("utf-8", subject)
  103. body := `From: "{shortTopicURL}" <{from}>
  104. To: {to}
  105. Subject: {subject}
  106. Content-Type: text/plain; charset="utf-8"
  107. {message}
  108. --
  109. This message was sent by {ip} at {time} via {topicURL}`
  110. body = strings.ReplaceAll(body, "{from}", from)
  111. body = strings.ReplaceAll(body, "{to}", to)
  112. body = strings.ReplaceAll(body, "{subject}", subject)
  113. body = strings.ReplaceAll(body, "{message}", message)
  114. body = strings.ReplaceAll(body, "{topicURL}", topicURL)
  115. body = strings.ReplaceAll(body, "{shortTopicURL}", util.ShortTopicURL(topicURL))
  116. body = strings.ReplaceAll(body, "{time}", time.Unix(m.Time, 0).UTC().Format(time.RFC1123))
  117. body = strings.ReplaceAll(body, "{ip}", senderIP)
  118. return body, nil
  119. }
  120. var (
  121. //go:embed "mailer_emoji.json"
  122. emojisJSON string
  123. )
  124. type emoji struct {
  125. Emoji string `json:"emoji"`
  126. Aliases []string `json:"aliases"`
  127. }
  128. func toEmojis(tags []string) (emojisOut []string, tagsOut []string, err error) {
  129. var emojis []emoji
  130. if err = json.Unmarshal([]byte(emojisJSON), &emojis); err != nil {
  131. return nil, nil, err
  132. }
  133. tagsOut = make([]string, 0)
  134. emojisOut = make([]string, 0)
  135. nextTag:
  136. for _, t := range tags { // TODO Super inefficient; we should just create a .json file with a map
  137. for _, e := range emojis {
  138. if util.Contains(e.Aliases, t) {
  139. emojisOut = append(emojisOut, e.Emoji)
  140. continue nextTag
  141. }
  142. }
  143. tagsOut = append(tagsOut, t)
  144. }
  145. return
  146. }