mailer.go 6.5 KB

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