mailer.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 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 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 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 err
  129. }
  130. }
  131. }
  132. if err = client.Mail(from); err != nil {
  133. return err
  134. }
  135. for _, rec := range to {
  136. if err = client.Rcpt(rec); err != nil {
  137. return err
  138. }
  139. }
  140. w, err := client.Data()
  141. if err != nil {
  142. return err
  143. } else if _, err = msg.WriteTo(w); err != nil {
  144. return err
  145. } else if err = w.Close(); err != nil {
  146. return 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. }