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.

mailer.go 5.5KB

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