mailer.go 5.0 KB

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