You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
4.7 KiB

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