send.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package email
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. log "github.com/sirupsen/logrus"
  6. "io"
  7. "net/http"
  8. "pmail/config"
  9. "pmail/db"
  10. "pmail/dto"
  11. "pmail/dto/parsemail"
  12. "pmail/dto/response"
  13. "pmail/hooks"
  14. "pmail/i18n"
  15. "pmail/smtp_server"
  16. "pmail/utils/async"
  17. "strings"
  18. "time"
  19. )
  20. type sendRequest struct {
  21. ReplyTo []user `json:"reply_to"`
  22. From user `json:"from"`
  23. To []user `json:"to"`
  24. Bcc []user `json:"bcc"`
  25. Cc []user `json:"cc"`
  26. Subject string `json:"subject"`
  27. Text string `json:"text"` // Plaintext message (optional)
  28. HTML string `json:"html"` // Html message (optional)
  29. Sender user `json:"sender"` // override From as SMTP envelope sender (optional)
  30. ReadReceipt []string `json:"read_receipt"`
  31. Attachments []attachment `json:"attrs"`
  32. }
  33. type user struct {
  34. Name string `json:"name"`
  35. Email string `json:"email"`
  36. }
  37. type attachment struct {
  38. Name string `json:"name"`
  39. Data string `json:"data"`
  40. }
  41. func Send(ctx *dto.Context, w http.ResponseWriter, req *http.Request) {
  42. reqBytes, err := io.ReadAll(req.Body)
  43. if err != nil {
  44. log.WithContext(ctx).Errorf("%+v", err)
  45. response.NewErrorResponse(response.ParamsError, "params error", err.Error()).FPrint(w)
  46. return
  47. }
  48. log.WithContext(ctx).Infof("发送邮件")
  49. var reqData sendRequest
  50. err = json.Unmarshal(reqBytes, &reqData)
  51. if err != nil {
  52. log.WithContext(ctx).Errorf("%+v", err)
  53. response.NewErrorResponse(response.ParamsError, "params error", err.Error()).FPrint(w)
  54. return
  55. }
  56. if reqData.From.Email == "" && reqData.From.Name != "" {
  57. reqData.From.Email = reqData.From.Name + "@" + config.Instance.Domain
  58. }
  59. if reqData.From.Email == "" {
  60. response.NewErrorResponse(response.ParamsError, "发件人必填", "发件人必填").FPrint(w)
  61. return
  62. }
  63. if reqData.Subject == "" {
  64. response.NewErrorResponse(response.ParamsError, "邮件标题必填", "邮件标题必填").FPrint(w)
  65. return
  66. }
  67. if len(reqData.To) <= 0 {
  68. response.NewErrorResponse(response.ParamsError, "收件人必填", "收件人必填").FPrint(w)
  69. return
  70. }
  71. e := &parsemail.Email{}
  72. for _, to := range reqData.To {
  73. e.To = append(e.To, &parsemail.User{
  74. Name: to.Name,
  75. EmailAddress: to.Email,
  76. })
  77. }
  78. for _, bcc := range reqData.Bcc {
  79. e.Bcc = append(e.Bcc, &parsemail.User{
  80. Name: bcc.Name,
  81. EmailAddress: bcc.Email,
  82. })
  83. }
  84. for _, cc := range reqData.Cc {
  85. e.Cc = append(e.Cc, &parsemail.User{
  86. Name: cc.Name,
  87. EmailAddress: cc.Email,
  88. })
  89. }
  90. e.From = &parsemail.User{
  91. Name: reqData.From.Name,
  92. EmailAddress: reqData.From.Email,
  93. }
  94. e.Text = []byte(reqData.Text)
  95. e.HTML = []byte(reqData.HTML)
  96. e.Subject = reqData.Subject
  97. for _, att := range reqData.Attachments {
  98. att.Data = strings.TrimPrefix(att.Data, "data:")
  99. infos := strings.Split(att.Data, ";")
  100. contentType := infos[0]
  101. content := strings.TrimPrefix(infos[1], "base64,")
  102. decoded, err := base64.StdEncoding.DecodeString(content)
  103. if err != nil {
  104. log.WithContext(ctx).Errorf("附件解码错误!%v", err)
  105. response.NewErrorResponse(response.ParamsError, i18n.GetText(ctx.Lang, "att_err"), err.Error()).FPrint(w)
  106. return
  107. }
  108. e.Attachments = append(e.Attachments, &parsemail.Attachment{
  109. Filename: att.Name,
  110. ContentType: contentType,
  111. Content: decoded,
  112. })
  113. }
  114. as := async.New(ctx)
  115. for _, hook := range hooks.HookList {
  116. if hook == nil {
  117. continue
  118. }
  119. as.WaitProcess(func(hk any) {
  120. hk.(hooks.EmailHook).SendBefore(ctx, e)
  121. }, hook)
  122. }
  123. as.Wait()
  124. // 邮件落库
  125. sql := "INSERT INTO email (type,subject, reply_to, from_name, from_address, `to`, bcc, cc, text, html, sender, attachments,spf_check, dkim_check, create_time,send_user_id,error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  126. sqlRes, sqlerr := db.Instance.Exec(db.WithContext(ctx, sql),
  127. 1,
  128. e.Subject,
  129. json2string(e.ReplyTo),
  130. e.From.Name,
  131. e.From.EmailAddress,
  132. json2string(e.To),
  133. json2string(e.Bcc),
  134. json2string(e.Cc),
  135. e.Text,
  136. e.HTML,
  137. json2string(e.Sender),
  138. json2string(e.Attachments),
  139. 1,
  140. 1,
  141. time.Now(),
  142. ctx.UserInfo.ID,
  143. "",
  144. )
  145. emailId, _ := sqlRes.LastInsertId()
  146. if sqlerr != nil || emailId <= 0 {
  147. log.Println("mysql insert error:", err.Error())
  148. response.NewErrorResponse(response.ServerError, i18n.GetText(ctx.Lang, "send_fail"), err.Error()).FPrint(w)
  149. return
  150. }
  151. async.New(ctx).Process(func(p any) {
  152. errMsg := ""
  153. err, sendErr := smtp_server.Send(ctx, e)
  154. as2 := async.New(ctx)
  155. for _, hook := range hooks.HookList {
  156. if hook == nil {
  157. continue
  158. }
  159. as2.WaitProcess(func(hk any) {
  160. hk.(hooks.EmailHook).SendAfter(ctx, e, sendErr)
  161. }, hook)
  162. }
  163. if err != nil {
  164. errMsg = err.Error()
  165. _, err := db.Instance.Exec(db.WithContext(ctx, "update email set status =2 ,error=? where id = ? "), errMsg, emailId)
  166. if err != nil {
  167. log.WithContext(ctx).Errorf("sql Error :%+v", err)
  168. }
  169. } else {
  170. _, err := db.Instance.Exec(db.WithContext(ctx, "update email set status =1 where id = ? "), emailId)
  171. if err != nil {
  172. log.WithContext(ctx).Errorf("sql Error :%+v", err)
  173. }
  174. }
  175. }, nil)
  176. response.NewSuccessResponse(i18n.GetText(ctx.Lang, "succ")).FPrint(w)
  177. }
  178. func json2string(d any) string {
  179. by, _ := json.Marshal(d)
  180. return string(by)
  181. }