mailer.go 5.6 KB

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