mailer.go 5.7 KB

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