mailer.go 4.4 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/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.Section("mailer").Key("SEND_BUFFER_LEN").MustInt(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. tlsconfig := &tls.Config{
  65. InsecureSkipVerify: settings.SkipVerify,
  66. ServerName: host,
  67. }
  68. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  69. if err != nil {
  70. return err
  71. }
  72. defer conn.Close()
  73. isSecureConn := false
  74. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  75. if strings.HasSuffix(port, "465") {
  76. conn = tls.Client(conn, tlsconfig)
  77. isSecureConn = true
  78. }
  79. client, err := smtp.NewClient(conn, host)
  80. if err != nil {
  81. return err
  82. }
  83. // If not using SMTPS, alway use STARTTLS if available
  84. hasStartTLS, _ := client.Extension("STARTTLS")
  85. if !isSecureConn && hasStartTLS {
  86. if err = client.StartTLS(tlsconfig); err != nil {
  87. return err
  88. }
  89. }
  90. canAuth, options := client.Extension("AUTH")
  91. if canAuth && len(settings.User) > 0 {
  92. var auth smtp.Auth
  93. if strings.Contains(options, "CRAM-MD5") {
  94. auth = smtp.CRAMMD5Auth(settings.User, settings.Passwd)
  95. } else if strings.Contains(options, "PLAIN") {
  96. auth = smtp.PlainAuth("", settings.User, settings.Passwd, host)
  97. }
  98. if auth != nil {
  99. if err = client.Auth(auth); err != nil {
  100. return err
  101. }
  102. }
  103. }
  104. if fromAddress, err := mail.ParseAddress(settings.From); err != nil {
  105. return err
  106. } else {
  107. if err = client.Mail(fromAddress.Address); err != nil {
  108. return err
  109. }
  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, []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.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. }