mailer.go 4.4 KB

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