message.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package email
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/smtp"
  11. "os"
  12. "strings"
  13. "time"
  14. "github.com/jaytaylor/html2text"
  15. "gopkg.in/gomail.v2"
  16. log "unknwon.dev/clog/v2"
  17. "gogs.io/gogs/internal/conf"
  18. )
  19. type Message struct {
  20. Info string // Message information for log purpose.
  21. *gomail.Message
  22. confirmChan chan struct{}
  23. }
  24. // NewMessageFrom creates new mail message object with custom From header.
  25. func NewMessageFrom(to []string, from, subject, htmlBody string) *Message {
  26. log.Trace("NewMessageFrom (htmlBody):\n%s", htmlBody)
  27. msg := gomail.NewMessage()
  28. msg.SetHeader("From", from)
  29. msg.SetHeader("To", to...)
  30. msg.SetHeader("Subject", conf.Email.SubjectPrefix+subject)
  31. msg.SetDateHeader("Date", time.Now())
  32. contentType := "text/html"
  33. body := htmlBody
  34. switchedToPlaintext := false
  35. if conf.Email.UsePlainText || conf.Email.AddPlainTextAlt {
  36. plainBody, err := html2text.FromString(htmlBody)
  37. if err != nil {
  38. log.Error("html2text.FromString: %v", err)
  39. } else {
  40. contentType = "text/plain"
  41. body = plainBody
  42. switchedToPlaintext = true
  43. }
  44. }
  45. msg.SetBody(contentType, body)
  46. if switchedToPlaintext && conf.Email.AddPlainTextAlt && !conf.Email.UsePlainText {
  47. // The AddAlternative method name is confusing - adding html as an "alternative" will actually cause mail
  48. // clients to show it as first priority, and the text "main body" is the 2nd priority fallback.
  49. // See: https://godoc.org/gopkg.in/gomail.v2#Message.AddAlternative
  50. msg.AddAlternative("text/html", htmlBody)
  51. }
  52. return &Message{
  53. Message: msg,
  54. confirmChan: make(chan struct{}),
  55. }
  56. }
  57. // NewMessage creates new mail message object with default From header.
  58. func NewMessage(to []string, subject, body string) *Message {
  59. return NewMessageFrom(to, conf.Email.From, subject, body)
  60. }
  61. type loginAuth struct {
  62. username, password string
  63. }
  64. // SMTP AUTH LOGIN Auth Handler
  65. func LoginAuth(username, password string) smtp.Auth {
  66. return &loginAuth{username, password}
  67. }
  68. func (*loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
  69. return "LOGIN", []byte{}, nil
  70. }
  71. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  72. if more {
  73. switch string(fromServer) {
  74. case "Username:":
  75. return []byte(a.username), nil
  76. case "Password:":
  77. return []byte(a.password), nil
  78. default:
  79. return nil, fmt.Errorf("unknwon fromServer: %s", string(fromServer))
  80. }
  81. }
  82. return nil, nil
  83. }
  84. type Sender struct{}
  85. func (*Sender) Send(from string, to []string, msg io.WriterTo) error {
  86. opts := conf.Email
  87. host, port, err := net.SplitHostPort(opts.Host)
  88. if err != nil {
  89. return err
  90. }
  91. tlsconfig := &tls.Config{
  92. InsecureSkipVerify: opts.SkipVerify,
  93. ServerName: host,
  94. }
  95. if opts.UseCertificate {
  96. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  97. if err != nil {
  98. return err
  99. }
  100. tlsconfig.Certificates = []tls.Certificate{cert}
  101. }
  102. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  103. if err != nil {
  104. return err
  105. }
  106. defer conn.Close()
  107. isSecureConn := false
  108. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  109. if strings.HasSuffix(port, "465") {
  110. conn = tls.Client(conn, tlsconfig)
  111. isSecureConn = true
  112. }
  113. client, err := smtp.NewClient(conn, host)
  114. if err != nil {
  115. return fmt.Errorf("NewClient: %v", err)
  116. }
  117. if !opts.DisableHELO {
  118. hostname := opts.HELOHostname
  119. if hostname == "" {
  120. hostname, err = os.Hostname()
  121. if err != nil {
  122. return err
  123. }
  124. }
  125. if err = client.Hello(hostname); err != nil {
  126. return fmt.Errorf("Hello: %v", err)
  127. }
  128. }
  129. // If not using SMTPS, always use STARTTLS if available
  130. hasStartTLS, _ := client.Extension("STARTTLS")
  131. if !isSecureConn && hasStartTLS {
  132. if err = client.StartTLS(tlsconfig); err != nil {
  133. return fmt.Errorf("StartTLS: %v", err)
  134. }
  135. }
  136. canAuth, options := client.Extension("AUTH")
  137. if canAuth && len(opts.User) > 0 {
  138. var auth smtp.Auth
  139. if strings.Contains(options, "CRAM-MD5") {
  140. auth = smtp.CRAMMD5Auth(opts.User, opts.Password)
  141. } else if strings.Contains(options, "PLAIN") {
  142. auth = smtp.PlainAuth("", opts.User, opts.Password, host)
  143. } else if strings.Contains(options, "LOGIN") {
  144. // Patch for AUTH LOGIN
  145. auth = LoginAuth(opts.User, opts.Password)
  146. }
  147. if auth != nil {
  148. if err = client.Auth(auth); err != nil {
  149. return fmt.Errorf("Auth: %v", err)
  150. }
  151. }
  152. }
  153. if err = client.Mail(from); err != nil {
  154. return fmt.Errorf("Mail: %v", err)
  155. }
  156. for _, rec := range to {
  157. if err = client.Rcpt(rec); err != nil {
  158. return fmt.Errorf("Rcpt: %v", err)
  159. }
  160. }
  161. w, err := client.Data()
  162. if err != nil {
  163. return fmt.Errorf("Data: %v", err)
  164. } else if _, err = msg.WriteTo(w); err != nil {
  165. return fmt.Errorf("WriteTo: %v", err)
  166. } else if err = w.Close(); err != nil {
  167. return fmt.Errorf("Close: %v", err)
  168. }
  169. return client.Quit()
  170. }
  171. func processMailQueue() {
  172. sender := &Sender{}
  173. for msg := range mailQueue {
  174. log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
  175. if err := gomail.Send(sender, msg.Message); err != nil {
  176. log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
  177. } else {
  178. log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
  179. }
  180. msg.confirmChan <- struct{}{}
  181. }
  182. }
  183. var mailQueue chan *Message
  184. // NewContext initializes settings for mailer.
  185. func NewContext() {
  186. // Need to check if mailQueue is nil because in during reinstall (user had installed
  187. // before but switched install lock off), this function will be called again
  188. // while mail queue is already processing tasks, and produces a race condition.
  189. if !conf.Email.Enabled || mailQueue != nil {
  190. return
  191. }
  192. mailQueue = make(chan *Message, 1000)
  193. go processMailQueue()
  194. }
  195. // Send puts new message object into mail queue.
  196. // It returns without confirmation (mail processed asynchronously) in normal cases,
  197. // but waits/blocks under hook mode to make sure mail has been sent.
  198. func Send(msg *Message) {
  199. if !conf.Email.Enabled {
  200. return
  201. }
  202. mailQueue <- msg
  203. if conf.HookMode {
  204. <-msg.confirmChan
  205. return
  206. }
  207. go func() {
  208. <-msg.confirmChan
  209. }()
  210. }