mailer.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "net"
  9. "net/smtp"
  10. "strings"
  11. "github.com/gogits/gogs/modules/log"
  12. "github.com/gogits/gogs/modules/setting"
  13. )
  14. type Message struct {
  15. To []string
  16. From string
  17. Subject string
  18. Body string
  19. User string
  20. Type string
  21. Massive bool
  22. Info string
  23. }
  24. // create mail content
  25. func (m Message) Content() string {
  26. // set mail type
  27. contentType := "text/plain; charset=UTF-8"
  28. if m.Type == "html" {
  29. contentType = "text/html; charset=UTF-8"
  30. }
  31. // create mail content
  32. content := "From: " + m.From +"\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
  33. return content
  34. }
  35. var mailQueue chan *Message
  36. func NewMailerContext() {
  37. mailQueue = make(chan *Message, setting.Cfg.MustInt("mailer", "SEND_BUFFER_LEN", 10))
  38. go processMailQueue()
  39. }
  40. func processMailQueue() {
  41. for {
  42. select {
  43. case msg := <-mailQueue:
  44. num, err := Send(msg)
  45. tos := strings.Join(msg.To, "; ")
  46. info := ""
  47. if err != nil {
  48. if len(msg.Info) > 0 {
  49. info = ", info: " + msg.Info
  50. }
  51. log.Error(4, fmt.Sprintf("Async sent email %d succeed, not send emails: %s%s err: %s", num, tos, info, err))
  52. } else {
  53. log.Trace(fmt.Sprintf("Async sent email %d succeed, sent emails: %s%s", num, tos, info))
  54. }
  55. }
  56. }
  57. }
  58. // sendMail allows mail with self-signed certificates.
  59. func sendMail(settings *setting.Mailer, from string, recipients []string, msgContent []byte) error {
  60. host, port, err := net.SplitHostPort(settings.Host)
  61. if err != nil {
  62. return err
  63. }
  64. if len(port) == 0 {
  65. port = "587"
  66. }
  67. tlsconfig := &tls.Config{
  68. InsecureSkipVerify: settings.SkipVerify,
  69. ServerName: host,
  70. }
  71. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  72. if err != nil {
  73. return err
  74. }
  75. defer conn.Close()
  76. isSecureConn := false
  77. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  78. if strings.HasSuffix(port, "465") {
  79. conn = tls.Client(conn, tlsconfig)
  80. isSecureConn = true
  81. }
  82. client, err := smtp.NewClient(conn, host)
  83. if err != nil {
  84. return err
  85. }
  86. // If not using SMTPS, alway use STARTTLS if available
  87. hasStartTLS, _ := client.Extension("STARTTLS")
  88. if !isSecureConn && hasStartTLS {
  89. if err = client.StartTLS(tlsconfig); err != nil {
  90. return err
  91. }
  92. }
  93. canAuth, options := client.Extension("AUTH")
  94. if canAuth && len(settings.User) > 0 {
  95. var auth smtp.Auth
  96. if strings.Contains(options, "CRAM-MD5") {
  97. auth = smtp.CRAMMD5Auth(settings.User, settings.Passwd)
  98. } else if strings.Contains(options, "PLAIN") {
  99. auth = smtp.PlainAuth("", settings.User, settings.Passwd, host)
  100. }
  101. if auth != nil {
  102. if err = client.Auth(auth); err != nil {
  103. return err
  104. }
  105. }
  106. }
  107. if err = client.Mail(from); err != nil {
  108. return err
  109. }
  110. for _, rec := range recipients {
  111. if err = client.Rcpt(rec); err != nil {
  112. return err
  113. }
  114. }
  115. w, err := client.Data()
  116. if err != nil {
  117. return err
  118. }
  119. if _, err = w.Write([]byte(msgContent)); err != nil {
  120. return err
  121. }
  122. if err = w.Close(); err != nil {
  123. return err
  124. }
  125. return client.Quit()
  126. }
  127. // Direct Send mail message
  128. func Send(msg *Message) (int, error) {
  129. log.Trace("Sending mails to: %s", strings.Join(msg.To, "; "))
  130. // get message body
  131. content := msg.Content()
  132. if len(msg.To) == 0 {
  133. return 0, fmt.Errorf("empty receive emails")
  134. } else if len(msg.Body) == 0 {
  135. return 0, fmt.Errorf("empty email body")
  136. }
  137. if msg.Massive {
  138. // send mail to multiple emails one by one
  139. num := 0
  140. for _, to := range msg.To {
  141. body := []byte("To: " + to + "\r\n" + content)
  142. err := sendMail(setting.MailService, msg.From, []string{to}, body)
  143. if err != nil {
  144. return num, err
  145. }
  146. num++
  147. }
  148. return num, nil
  149. } else {
  150. body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content)
  151. // send to multiple emails in one message
  152. err := sendMail(setting.MailService, msg.From, msg.To, body)
  153. if err != nil {
  154. return 0, err
  155. } else {
  156. return 1, nil
  157. }
  158. }
  159. }
  160. // Async Send mail message
  161. func SendAsync(msg *Message) {
  162. go func() {
  163. mailQueue <- msg
  164. }()
  165. }
  166. // Create html mail message
  167. func NewHtmlMessage(To []string, From, Subject, Body string) Message {
  168. return Message{
  169. To: To,
  170. From: From,
  171. Subject: Subject,
  172. Body: Body,
  173. Type: "html",
  174. }
  175. }