smtp_sender.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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/v2/log"
  13. "heckel.io/ntfy/v2/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. date := time.Unix(m.Time, 0).UTC().Format(time.RFC1123Z)
  106. subject = mime.BEncoding.Encode("utf-8", subject)
  107. body := `From: "{shortTopicURL}" <{from}>
  108. To: {to}
  109. Date: {date}
  110. Subject: {subject}
  111. Content-Type: text/plain; charset="utf-8"
  112. {message}
  113. --
  114. This message was sent by {ip} at {time} via {topicURL}`
  115. body = strings.ReplaceAll(body, "{from}", from)
  116. body = strings.ReplaceAll(body, "{to}", to)
  117. body = strings.ReplaceAll(body, "{date}", date)
  118. body = strings.ReplaceAll(body, "{subject}", subject)
  119. body = strings.ReplaceAll(body, "{message}", message)
  120. body = strings.ReplaceAll(body, "{topicURL}", topicURL)
  121. body = strings.ReplaceAll(body, "{shortTopicURL}", util.ShortTopicURL(topicURL))
  122. body = strings.ReplaceAll(body, "{time}", time.Unix(m.Time, 0).UTC().Format(time.RFC1123))
  123. body = strings.ReplaceAll(body, "{ip}", senderIP)
  124. return body, nil
  125. }
  126. var (
  127. //go:embed "mailer_emoji_map.json"
  128. emojisJSON string
  129. )
  130. func toEmojis(tags []string) (emojisOut []string, tagsOut []string, err error) {
  131. var emojiMap map[string]string
  132. if err = json.Unmarshal([]byte(emojisJSON), &emojiMap); err != nil {
  133. return nil, nil, err
  134. }
  135. tagsOut = make([]string, 0)
  136. emojisOut = make([]string, 0)
  137. for _, t := range tags {
  138. if emoji, ok := emojiMap[t]; ok {
  139. emojisOut = append(emojisOut, emoji)
  140. } else {
  141. tagsOut = append(tagsOut, t)
  142. }
  143. }
  144. return
  145. }