You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2020 The Gitea 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 private
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "code.gitea.io/gitea/modules/setting"
  11. )
  12. // Email structure holds a data for sending general emails
  13. type Email struct {
  14. Subject string
  15. Message string
  16. To []string
  17. }
  18. // SendEmail calls the internal SendEmail function
  19. //
  20. // It accepts a list of usernames.
  21. // If DB contains these users it will send the email to them.
  22. //
  23. // If to list == nil its supposed to send an email to every
  24. // user present in DB
  25. func SendEmail(subject, message string, to []string) (int, string) {
  26. reqURL := setting.LocalURL + "api/internal/mail/send"
  27. req := newInternalRequest(reqURL, "POST")
  28. req = req.Header("Content-Type", "application/json")
  29. jsonBytes, _ := json.Marshal(Email{
  30. Subject: subject,
  31. Message: message,
  32. To: to,
  33. })
  34. req.Body(jsonBytes)
  35. resp, err := req.Response()
  36. if err != nil {
  37. return http.StatusInternalServerError, fmt.Sprintf("Unable to contact gitea: %v", err.Error())
  38. }
  39. defer resp.Body.Close()
  40. body, err := ioutil.ReadAll(resp.Body)
  41. if err != nil {
  42. return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error())
  43. }
  44. var users = fmt.Sprintf("%d", len(to))
  45. if len(to) == 0 {
  46. users = "all"
  47. }
  48. return http.StatusOK, fmt.Sprintf("Sent %s email(s) to %s users", body, users)
  49. }