mailer.go 5.7 KB

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