mailer.go 5.5 KB

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