mailer.go 6.4 KB

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