mailer.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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/mail"
  10. "net/smtp"
  11. "strings"
  12. "github.com/gogits/gogs/modules/log"
  13. "github.com/gogits/gogs/modules/setting"
  14. )
  15. type Message struct {
  16. To []string
  17. From string
  18. Subject string
  19. Body 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, 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 fromAddress, err := mail.ParseAddress(settings.From); err != nil {
  108. return err
  109. } else {
  110. if err = client.Mail(fromAddress.Address); err != nil {
  111. return err
  112. }
  113. }
  114. for _, rec := range recipients {
  115. if err = client.Rcpt(rec); err != nil {
  116. return err
  117. }
  118. }
  119. w, err := client.Data()
  120. if err != nil {
  121. return err
  122. }
  123. if _, err = w.Write([]byte(msgContent)); err != nil {
  124. return err
  125. }
  126. if err = w.Close(); err != nil {
  127. return err
  128. }
  129. return client.Quit()
  130. }
  131. // Direct Send mail message
  132. func Send(msg *Message) (int, error) {
  133. log.Trace("Sending mails to: %s", strings.Join(msg.To, "; "))
  134. // get message body
  135. content := msg.Content()
  136. if len(msg.To) == 0 {
  137. return 0, fmt.Errorf("empty receive emails")
  138. } else if len(msg.Body) == 0 {
  139. return 0, fmt.Errorf("empty email body")
  140. }
  141. if msg.Massive {
  142. // send mail to multiple emails one by one
  143. num := 0
  144. for _, to := range msg.To {
  145. body := []byte("To: " + to + "\r\n" + content)
  146. err := sendMail(setting.MailService, []string{to}, body)
  147. if err != nil {
  148. return num, err
  149. }
  150. num++
  151. }
  152. return num, nil
  153. } else {
  154. body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content)
  155. // send to multiple emails in one message
  156. err := sendMail(setting.MailService, msg.To, body)
  157. if err != nil {
  158. return 0, err
  159. } else {
  160. return 1, nil
  161. }
  162. }
  163. }
  164. // Async Send mail message
  165. func SendAsync(msg *Message) {
  166. go func() {
  167. mailQueue <- msg
  168. }()
  169. }
  170. // Create html mail message
  171. func NewHtmlMessage(To []string, From, Subject, Body string) Message {
  172. return Message{
  173. To: To,
  174. From: From,
  175. Subject: Subject,
  176. Body: Body,
  177. Type: "html",
  178. }
  179. }