mail.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package http
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "go-common/app/admin/main/macross/model/mail"
  6. "go-common/library/ecode"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "io/ioutil"
  10. )
  11. // sendMail send mail
  12. func sendmail(c *bm.Context) {
  13. req := c.Request
  14. res := map[string]interface{}{}
  15. res["message"] = "success"
  16. var attach *mail.Attach
  17. // 附件
  18. file, header, err := c.Request.FormFile("file")
  19. if err == nil {
  20. defer file.Close()
  21. attach = &mail.Attach{}
  22. attach.Name = header.Filename
  23. attach.File = file
  24. unzip := c.Request.Form.Get("unzip")
  25. if unzip != "" && unzip != "0" {
  26. attach.ShouldUnzip = true
  27. } else {
  28. attach.ShouldUnzip = false
  29. }
  30. }
  31. var bs []byte
  32. if attach == nil {
  33. bs, err = ioutil.ReadAll(req.Body)
  34. } else {
  35. // 使用 multipart 上传附件时,body 并不是 json,因此原来的 json 放在 form 的 json_body 中
  36. jsonBody := c.Request.Form.Get("json_body")
  37. bs = []byte(jsonBody)
  38. }
  39. if err != nil {
  40. log.Error("ioutil.ReadAll() error(%v)", err)
  41. res["message"] = fmt.Sprintf("%v", err)
  42. c.JSONMap(res, ecode.RequestErr)
  43. return
  44. }
  45. req.Body.Close()
  46. // params
  47. var m = &mail.Mail{}
  48. if err = json.Unmarshal(bs, m); err != nil {
  49. log.Error("http sendmail() json.Unmarshal(%s) error(%v)", string(bs), err)
  50. res["message"] = fmt.Sprintf("%v", err)
  51. c.JSONMap(res, ecode.RequestErr)
  52. return
  53. }
  54. if m.Subject == "" || m.Body == "" || len(m.ToAddresses) == 0 {
  55. res["message"] = fmt.Sprintf("%v", err)
  56. c.JSONMap(res, ecode.RequestErr)
  57. return
  58. }
  59. if err = svr.SendMail(c, m, attach); err != nil {
  60. res["message"] = fmt.Sprintf("%v", err)
  61. c.JSONMap(res, err)
  62. return
  63. }
  64. c.JSONMap(res, nil)
  65. }