smtp_sender.go 3.8 KB

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