Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

mailer.go 5.6KB

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