message.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package email
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "strconv"
  6. "strings"
  7. "github.com/cockroachdb/errors"
  8. "github.com/inbucket/html2text"
  9. gomail "github.com/wneessen/go-mail"
  10. log "unknwon.dev/clog/v2"
  11. "gogs.io/gogs/internal/conf"
  12. )
  13. type message struct {
  14. info string
  15. msg *gomail.Msg
  16. confirmChan chan struct{}
  17. }
  18. func newMessageFrom(to []string, from, subject, htmlBody string) (*message, error) {
  19. log.Trace("NewMessageFrom (htmlBody):\n%s", htmlBody)
  20. m := gomail.NewMsg()
  21. if err := m.From(from); err != nil {
  22. return nil, errors.Wrapf(err, "set From address %q", from)
  23. }
  24. if err := m.To(to...); err != nil {
  25. return nil, errors.Wrap(err, "set To addresses")
  26. }
  27. m.Subject(conf.Email.SubjectPrefix + subject)
  28. m.SetDate()
  29. if conf.Email.UsePlainText || conf.Email.AddPlainTextAlt {
  30. plainBody, err := html2text.FromString(htmlBody)
  31. if err != nil {
  32. return nil, errors.Wrap(err, "convert HTML to plain text")
  33. }
  34. if conf.Email.UsePlainText {
  35. m.SetBodyString(gomail.TypeTextPlain, plainBody)
  36. } else {
  37. m.SetBodyString(gomail.TypeTextPlain, plainBody)
  38. m.AddAlternativeString(gomail.TypeTextHTML, htmlBody)
  39. }
  40. } else {
  41. m.SetBodyString(gomail.TypeTextHTML, htmlBody)
  42. }
  43. return &message{
  44. msg: m,
  45. confirmChan: make(chan struct{}),
  46. }, nil
  47. }
  48. func newMessage(to []string, subject, body string) (*message, error) {
  49. return newMessageFrom(to, conf.Email.From, subject, body)
  50. }
  51. func newSMTPClient() (*gomail.Client, error) {
  52. opts := conf.Email
  53. host, portStr, err := net.SplitHostPort(opts.Host)
  54. if err != nil {
  55. return nil, err
  56. }
  57. port, err := strconv.Atoi(portStr)
  58. if err != nil {
  59. return nil, err
  60. }
  61. clientOpts := []gomail.Option{
  62. gomail.WithPort(port),
  63. }
  64. if port == 465 {
  65. clientOpts = append(clientOpts, gomail.WithSSL())
  66. } else {
  67. clientOpts = append(clientOpts, gomail.WithTLSPolicy(gomail.TLSOpportunistic))
  68. }
  69. if opts.HELOHostname != "" {
  70. clientOpts = append(clientOpts, gomail.WithHELO(opts.HELOHostname))
  71. }
  72. tlsconfig := &tls.Config{
  73. InsecureSkipVerify: opts.SkipVerify,
  74. ServerName: host,
  75. }
  76. if opts.UseCertificate {
  77. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  78. if err != nil {
  79. return nil, err
  80. }
  81. tlsconfig.Certificates = []tls.Certificate{cert}
  82. }
  83. clientOpts = append(clientOpts, gomail.WithTLSConfig(tlsconfig))
  84. if len(opts.User) > 0 {
  85. clientOpts = append(clientOpts,
  86. gomail.WithSMTPAuth(gomail.SMTPAuthAutoDiscover),
  87. gomail.WithUsername(opts.User),
  88. gomail.WithPassword(opts.Password),
  89. )
  90. }
  91. return gomail.NewClient(host, clientOpts...)
  92. }
  93. func sendMessage(msg *message) error {
  94. client, err := newSMTPClient()
  95. if err != nil {
  96. return err
  97. }
  98. return client.DialAndSend(msg.msg)
  99. }
  100. func processMailQueue() {
  101. for msg := range mailQueue {
  102. to := strings.Join(msg.msg.GetToString(), ", ")
  103. log.Trace("New e-mail sending request %s: %s", to, msg.info)
  104. if err := sendMessage(msg); err != nil {
  105. log.Error("Failed to send emails %s: %s - %v", to, msg.info, err)
  106. } else {
  107. log.Trace("E-mails sent %s: %s", to, msg.info)
  108. }
  109. msg.confirmChan <- struct{}{}
  110. }
  111. }
  112. var mailQueue chan *message
  113. // NewContext initializes settings for mailer.
  114. func NewContext() {
  115. // Need to check if mailQueue is nil because in during reinstall (user had installed
  116. // before but switched install lock off), this function will be called again
  117. // while mail queue is already processing tasks, and produces a race condition.
  118. if !conf.Email.Enabled || mailQueue != nil {
  119. return
  120. }
  121. mailQueue = make(chan *message, 1000)
  122. go processMailQueue()
  123. }
  124. // send puts new message object into mail queue.
  125. // It returns without confirmation (mail processed asynchronously) in normal cases,
  126. // but waits/blocks under hook mode to make sure mail has been sent.
  127. func send(msg *message) {
  128. if !conf.Email.Enabled {
  129. return
  130. }
  131. mailQueue <- msg
  132. if conf.HookMode {
  133. <-msg.confirmChan
  134. return
  135. }
  136. go func() {
  137. <-msg.confirmChan
  138. }()
  139. }