mailer.go 5.2 KB

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