smtp_sender.go 3.7 KB

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