mailer.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. "gogs.io/gogs/internal/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", setting.MailService.SubjectPrefix+subject)
  31. msg.SetDateHeader("Date", time.Now())
  32. contentType := "text/html"
  33. body := htmlBody
  34. switchedToPlaintext := false
  35. if setting.MailService.UsePlainText || setting.MailService.AddPlainTextAlt {
  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. switchedToPlaintext = true
  43. }
  44. }
  45. msg.SetBody(contentType, body)
  46. if switchedToPlaintext && setting.MailService.AddPlainTextAlt && !setting.MailService.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, setting.MailService.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 (a *loginAuth) Start(server *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. }
  86. func (s *Sender) Send(from string, to []string, msg io.WriterTo) error {
  87. opts := setting.MailService
  88. host, port, err := net.SplitHostPort(opts.Host)
  89. if err != nil {
  90. return err
  91. }
  92. tlsconfig := &tls.Config{
  93. InsecureSkipVerify: opts.SkipVerify,
  94. ServerName: host,
  95. }
  96. if opts.UseCertificate {
  97. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  98. if err != nil {
  99. return err
  100. }
  101. tlsconfig.Certificates = []tls.Certificate{cert}
  102. }
  103. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  104. if err != nil {
  105. return err
  106. }
  107. defer conn.Close()
  108. isSecureConn := false
  109. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  110. if strings.HasSuffix(port, "465") {
  111. conn = tls.Client(conn, tlsconfig)
  112. isSecureConn = true
  113. }
  114. client, err := smtp.NewClient(conn, host)
  115. if err != nil {
  116. return fmt.Errorf("NewClient: %v", err)
  117. }
  118. if !opts.DisableHelo {
  119. hostname := opts.HeloHostname
  120. if len(hostname) == 0 {
  121. hostname, err = os.Hostname()
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. if err = client.Hello(hostname); err != nil {
  127. return fmt.Errorf("Hello: %v", err)
  128. }
  129. }
  130. // If not using SMTPS, alway use STARTTLS if available
  131. hasStartTLS, _ := client.Extension("STARTTLS")
  132. if !isSecureConn && hasStartTLS {
  133. if err = client.StartTLS(tlsconfig); err != nil {
  134. return fmt.Errorf("StartTLS: %v", err)
  135. }
  136. }
  137. canAuth, options := client.Extension("AUTH")
  138. if canAuth && len(opts.User) > 0 {
  139. var auth smtp.Auth
  140. if strings.Contains(options, "CRAM-MD5") {
  141. auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
  142. } else if strings.Contains(options, "PLAIN") {
  143. auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
  144. } else if strings.Contains(options, "LOGIN") {
  145. // Patch for AUTH LOGIN
  146. auth = LoginAuth(opts.User, opts.Passwd)
  147. }
  148. if auth != nil {
  149. if err = client.Auth(auth); err != nil {
  150. return fmt.Errorf("Auth: %v", err)
  151. }
  152. }
  153. }
  154. if err = client.Mail(from); err != nil {
  155. return fmt.Errorf("Mail: %v", err)
  156. }
  157. for _, rec := range to {
  158. if err = client.Rcpt(rec); err != nil {
  159. return fmt.Errorf("Rcpt: %v", err)
  160. }
  161. }
  162. w, err := client.Data()
  163. if err != nil {
  164. return fmt.Errorf("Data: %v", err)
  165. } else if _, err = msg.WriteTo(w); err != nil {
  166. return fmt.Errorf("WriteTo: %v", err)
  167. } else if err = w.Close(); err != nil {
  168. return fmt.Errorf("Close: %v", err)
  169. }
  170. return client.Quit()
  171. }
  172. func processMailQueue() {
  173. sender := &Sender{}
  174. for {
  175. select {
  176. case msg := <-mailQueue:
  177. log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
  178. if err := gomail.Send(sender, msg.Message); err != nil {
  179. log.Error(3, "Fail to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
  180. } else {
  181. log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
  182. }
  183. msg.confirmChan <- struct{}{}
  184. }
  185. }
  186. }
  187. var mailQueue chan *Message
  188. // NewContext initializes settings for mailer.
  189. func NewContext() {
  190. // Need to check if mailQueue is nil because in during reinstall (user had installed
  191. // before but swithed install lock off), this function will be called again
  192. // while mail queue is already processing tasks, and produces a race condition.
  193. if setting.MailService == nil || mailQueue != nil {
  194. return
  195. }
  196. mailQueue = make(chan *Message, setting.MailService.QueueLength)
  197. go processMailQueue()
  198. }
  199. // Send puts new message object into mail queue.
  200. // It returns without confirmation (mail processed asynchronously) in normal cases,
  201. // but waits/blocks under hook mode to make sure mail has been sent.
  202. func Send(msg *Message) {
  203. mailQueue <- msg
  204. if setting.HookMode {
  205. <-msg.confirmChan
  206. return
  207. }
  208. go func() {
  209. <-msg.confirmChan
  210. }()
  211. }