mailer.go 4.3 KB

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