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.

283 lines
6.8 KiB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package mailer
  6. import (
  7. "crypto/tls"
  8. "fmt"
  9. "io"
  10. "net"
  11. "net/smtp"
  12. "os"
  13. "os/exec"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/jaytaylor/html2text"
  20. "gopkg.in/gomail.v2"
  21. )
  22. // Message mail body and log info
  23. type Message struct {
  24. Info string // Message information for log purpose.
  25. *gomail.Message
  26. }
  27. // NewMessageFrom creates new mail message object with custom From header.
  28. func NewMessageFrom(to []string, fromDisplayName, fromAddress, subject, body string) *Message {
  29. log.Trace("NewMessageFrom (body):\n%s", body)
  30. msg := gomail.NewMessage()
  31. msg.SetAddressHeader("From", fromAddress, fromDisplayName)
  32. msg.SetHeader("To", to...)
  33. msg.SetHeader("Subject", subject)
  34. msg.SetDateHeader("Date", time.Now())
  35. plainBody, err := html2text.FromString(body)
  36. if err != nil || setting.MailService.SendAsPlainText {
  37. if strings.Contains(base.TruncateString(body, 100), "<html>") {
  38. log.Warn("Mail contains HTML but configured to send as plain text.")
  39. }
  40. msg.SetBody("text/plain", plainBody)
  41. } else {
  42. msg.SetBody("text/plain", plainBody)
  43. msg.AddAlternative("text/html", body)
  44. }
  45. return &Message{
  46. Message: msg,
  47. }
  48. }
  49. // NewMessage creates new mail message object with default From header.
  50. func NewMessage(to []string, subject, body string) *Message {
  51. return NewMessageFrom(to, setting.MailService.FromName, setting.MailService.FromEmail, subject, body)
  52. }
  53. type loginAuth struct {
  54. username, password string
  55. }
  56. // LoginAuth SMTP AUTH LOGIN Auth Handler
  57. func LoginAuth(username, password string) smtp.Auth {
  58. return &loginAuth{username, password}
  59. }
  60. // Start start SMTP login auth
  61. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  62. return "LOGIN", []byte{}, nil
  63. }
  64. // Next next step of SMTP login auth
  65. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  66. if more {
  67. switch string(fromServer) {
  68. case "Username:":
  69. return []byte(a.username), nil
  70. case "Password:":
  71. return []byte(a.password), nil
  72. default:
  73. return nil, fmt.Errorf("unknown fromServer: %s", string(fromServer))
  74. }
  75. }
  76. return nil, nil
  77. }
  78. // Sender SMTP mail sender
  79. type smtpSender struct {
  80. }
  81. // Send send email
  82. func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
  83. opts := setting.MailService
  84. host, port, err := net.SplitHostPort(opts.Host)
  85. if err != nil {
  86. return err
  87. }
  88. tlsconfig := &tls.Config{
  89. InsecureSkipVerify: opts.SkipVerify,
  90. ServerName: host,
  91. }
  92. if opts.UseCertificate {
  93. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  94. if err != nil {
  95. return err
  96. }
  97. tlsconfig.Certificates = []tls.Certificate{cert}
  98. }
  99. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  100. if err != nil {
  101. return err
  102. }
  103. defer conn.Close()
  104. isSecureConn := false
  105. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  106. if strings.HasSuffix(port, "465") {
  107. conn = tls.Client(conn, tlsconfig)
  108. isSecureConn = true
  109. }
  110. client, err := smtp.NewClient(conn, host)
  111. if err != nil {
  112. return fmt.Errorf("NewClient: %v", err)
  113. }
  114. if !opts.DisableHelo {
  115. hostname := opts.HeloHostname
  116. if len(hostname) == 0 {
  117. hostname, err = os.Hostname()
  118. if err != nil {
  119. return err
  120. }
  121. }
  122. if err = client.Hello(hostname); err != nil {
  123. return fmt.Errorf("Hello: %v", err)
  124. }
  125. }
  126. // If not using SMTPS, always use STARTTLS if available
  127. hasStartTLS, _ := client.Extension("STARTTLS")
  128. if !isSecureConn && hasStartTLS {
  129. if err = client.StartTLS(tlsconfig); err != nil {
  130. return fmt.Errorf("StartTLS: %v", err)
  131. }
  132. }
  133. canAuth, options := client.Extension("AUTH")
  134. if canAuth && len(opts.User) > 0 {
  135. var auth smtp.Auth
  136. if strings.Contains(options, "CRAM-MD5") {
  137. auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
  138. } else if strings.Contains(options, "PLAIN") {
  139. auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
  140. } else if strings.Contains(options, "LOGIN") {
  141. // Patch for AUTH LOGIN
  142. auth = LoginAuth(opts.User, opts.Passwd)
  143. }
  144. if auth != nil {
  145. if err = client.Auth(auth); err != nil {
  146. return fmt.Errorf("Auth: %v", err)
  147. }
  148. }
  149. }
  150. if err = client.Mail(from); err != nil {
  151. return fmt.Errorf("Mail: %v", err)
  152. }
  153. for _, rec := range to {
  154. if err = client.Rcpt(rec); err != nil {
  155. return fmt.Errorf("Rcpt: %v", err)
  156. }
  157. }
  158. w, err := client.Data()
  159. if err != nil {
  160. return fmt.Errorf("Data: %v", err)
  161. } else if _, err = msg.WriteTo(w); err != nil {
  162. return fmt.Errorf("WriteTo: %v", err)
  163. } else if err = w.Close(); err != nil {
  164. return fmt.Errorf("Close: %v", err)
  165. }
  166. return client.Quit()
  167. }
  168. // Sender sendmail mail sender
  169. type sendmailSender struct {
  170. }
  171. // Send send email
  172. func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
  173. var err error
  174. var closeError error
  175. var waitError error
  176. args := []string{"-F", from, "-i"}
  177. args = append(args, to...)
  178. log.Trace("Sending with: %s %v", setting.MailService.SendmailPath, args)
  179. cmd := exec.Command(setting.MailService.SendmailPath, args...)
  180. pipe, err := cmd.StdinPipe()
  181. if err != nil {
  182. return err
  183. }
  184. if err = cmd.Start(); err != nil {
  185. return err
  186. }
  187. _, err = msg.WriteTo(pipe)
  188. // we MUST close the pipe or sendmail will hang waiting for more of the message
  189. // Also we should wait on our sendmail command even if something fails
  190. closeError = pipe.Close()
  191. waitError = cmd.Wait()
  192. if err != nil {
  193. return err
  194. } else if closeError != nil {
  195. return closeError
  196. } else {
  197. return waitError
  198. }
  199. }
  200. func processMailQueue() {
  201. for {
  202. select {
  203. case msg := <-mailQueue:
  204. log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
  205. if err := gomail.Send(Sender, msg.Message); err != nil {
  206. log.Error(3, "Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
  207. } else {
  208. log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
  209. }
  210. }
  211. }
  212. }
  213. var mailQueue chan *Message
  214. // Sender sender for sending mail synchronously
  215. var Sender gomail.Sender
  216. // NewContext start mail queue service
  217. func NewContext() {
  218. // Need to check if mailQueue is nil because in during reinstall (user had installed
  219. // before but swithed install lock off), this function will be called again
  220. // while mail queue is already processing tasks, and produces a race condition.
  221. if setting.MailService == nil || mailQueue != nil {
  222. return
  223. }
  224. if setting.MailService.UseSendmail {
  225. Sender = &sendmailSender{}
  226. } else {
  227. Sender = &smtpSender{}
  228. }
  229. mailQueue = make(chan *Message, setting.MailService.QueueLength)
  230. go processMailQueue()
  231. }
  232. // SendAsync send mail asynchronous
  233. func SendAsync(msg *Message) {
  234. go func() {
  235. mailQueue <- msg
  236. }()
  237. }