mailer.go 5.3 KB

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