web_push.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package web_push
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. "pmail/config"
  7. "pmail/dto/parsemail"
  8. "pmail/utils/context"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. type WebPushHook struct {
  12. url string
  13. token string
  14. }
  15. // EmailData 用于存储解析后的邮件数据
  16. type EmailData struct {
  17. From string `json:"from"`
  18. To []string `json:"to"`
  19. Subject string `json:"subject"`
  20. Body string `json:"body"`
  21. Token string `json:"token"`
  22. }
  23. func (w *WebPushHook) SendBefore(ctx *context.Context, email *parsemail.Email) {
  24. }
  25. func (w *WebPushHook) SendAfter(ctx *context.Context, email *parsemail.Email, err map[string]error) {
  26. }
  27. func (w *WebPushHook) ReceiveParseBefore(email []byte) {
  28. }
  29. func (w *WebPushHook) ReceiveParseAfter(email *parsemail.Email) {
  30. if w.url == "" {
  31. return
  32. }
  33. content := string(email.Text)
  34. if content == "" {
  35. content = email.Subject
  36. }
  37. webhookURL := w.url // 替换为您的 Webhook URL
  38. to := make([]string, len(email.To))
  39. for i, user := range email.To {
  40. to[i] = user.EmailAddress
  41. }
  42. data := EmailData{
  43. From: email.From.EmailAddress,
  44. To: to,
  45. Subject: email.Subject,
  46. Body: content,
  47. Token: w.token,
  48. }
  49. var ctx *context.Context = nil
  50. jsonData, err := json.Marshal(data)
  51. if err != nil {
  52. log.WithContext(ctx).Errorf("web push error %+v", err)
  53. }
  54. resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData))
  55. if err != nil {
  56. log.WithContext(ctx).Errorf("web push error %+v", err)
  57. }
  58. defer resp.Body.Close()
  59. }
  60. func NewWebPushHook() *WebPushHook {
  61. ret := &WebPushHook{
  62. url: config.Instance.WebPushUrl,
  63. token: config.Instance.WebPushToken,
  64. }
  65. return ret
  66. }