read_content.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package smtp_server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/mileusna/spf"
  6. log "github.com/sirupsen/logrus"
  7. "io"
  8. "net"
  9. "net/netip"
  10. "pmail/config"
  11. "pmail/db"
  12. "pmail/dto/parsemail"
  13. "pmail/hooks"
  14. "pmail/services/rule"
  15. "pmail/utils/array"
  16. "pmail/utils/async"
  17. "pmail/utils/context"
  18. "pmail/utils/send"
  19. "strings"
  20. "time"
  21. )
  22. func (s *Session) Data(r io.Reader) error {
  23. ctx := s.Ctx
  24. log.WithContext(ctx).Debugf("收到邮件")
  25. emailData, err := io.ReadAll(r)
  26. if err != nil {
  27. log.WithContext(ctx).Error("邮件内容无法读取", err)
  28. return err
  29. }
  30. as1 := async.New(ctx)
  31. for _, hook := range hooks.HookList {
  32. if hook == nil {
  33. continue
  34. }
  35. as1.WaitProcess(func(hk any) {
  36. hk.(hooks.EmailHook).ReceiveParseBefore(emailData)
  37. }, hook)
  38. }
  39. as1.Wait()
  40. log.WithContext(ctx).Infof("邮件原始内容: %s", emailData)
  41. email := parsemail.NewEmailFromReader(s.From, s.To, bytes.NewReader(emailData))
  42. // 判断是收信还是转发
  43. if array.InArray(email.From.GetDomain(), config.Instance.Domains) {
  44. // 转发
  45. err := saveEmail(ctx, email, 1, true, true)
  46. if err != nil {
  47. log.WithContext(ctx).Errorf("Email Save Error %v", err)
  48. }
  49. send.Send(ctx, email)
  50. } else {
  51. // 收件
  52. var dkimStatus, SPFStatus bool
  53. // DKIM校验
  54. dkimStatus = parsemail.Check(bytes.NewReader(emailData))
  55. if err != nil {
  56. log.WithContext(ctx).Errorf("邮件内容解析失败! Error : %v \n", err)
  57. }
  58. SPFStatus = spfCheck(s.RemoteAddress.String(), email.Sender, email.Sender.EmailAddress)
  59. saveEmail(ctx, email, 0, SPFStatus, dkimStatus)
  60. }
  61. return nil
  62. }
  63. func saveEmail(ctx *context.Context, email *parsemail.Email, emailType int, SPFStatus, dkimStatus bool) error {
  64. var dkimV, spfV int8
  65. if dkimStatus {
  66. dkimV = 1
  67. }
  68. if SPFStatus {
  69. spfV = 1
  70. }
  71. // 垃圾过滤
  72. if config.Instance.SpamFilterLevel == 1 && !SPFStatus && !dkimStatus {
  73. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  74. return nil
  75. }
  76. if config.Instance.SpamFilterLevel == 2 && !SPFStatus {
  77. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  78. return nil
  79. }
  80. log.WithContext(ctx).Debugf("开始执行插件!")
  81. as2 := async.New(ctx)
  82. for _, hook := range hooks.HookList {
  83. if hook == nil {
  84. continue
  85. }
  86. as2.WaitProcess(func(hk any) {
  87. hk.(hooks.EmailHook).ReceiveParseAfter(email)
  88. }, hook)
  89. }
  90. as2.Wait()
  91. log.WithContext(ctx).Debugf("开始执行邮件规则!")
  92. // 执行邮件规则
  93. rs := rule.GetAllRules(ctx)
  94. for _, r := range rs {
  95. if rule.MatchRule(ctx, r, email) {
  96. rule.DoRule(ctx, r, email)
  97. }
  98. }
  99. log.WithContext(ctx).Debugf("开始入库!")
  100. if email == nil {
  101. return nil
  102. }
  103. sql := "INSERT INTO email (type, send_date, subject, reply_to, from_name, from_address, `to`, bcc, cc, text, html, sender, attachments,spf_check, dkim_check, create_time,is_read,status,group_id) VALUES (?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  104. _, err := db.Instance.Exec(sql,
  105. emailType,
  106. email.Date,
  107. email.Subject,
  108. json2string(email.ReplyTo),
  109. email.From.Name,
  110. email.From.EmailAddress,
  111. json2string(email.To),
  112. json2string(email.Bcc),
  113. json2string(email.Cc),
  114. email.Text,
  115. email.HTML,
  116. json2string(email.Sender),
  117. json2string(email.Attachments),
  118. spfV,
  119. dkimV,
  120. time.Now(),
  121. email.IsRead,
  122. email.Status,
  123. email.GroupId,
  124. )
  125. if err != nil {
  126. log.WithContext(ctx).Println("mysql insert error:", err.Error())
  127. }
  128. return nil
  129. }
  130. func json2string(d any) string {
  131. by, _ := json.Marshal(d)
  132. return string(by)
  133. }
  134. func spfCheck(remoteAddress string, sender *parsemail.User, senderString string) bool {
  135. //spf校验
  136. ipAddress, _ := netip.ParseAddrPort(remoteAddress)
  137. ip := net.ParseIP(ipAddress.Addr().String())
  138. if ip.IsPrivate() {
  139. return true
  140. }
  141. tmp := strings.Split(sender.EmailAddress, "@")
  142. if len(tmp) < 2 {
  143. return false
  144. }
  145. res := spf.CheckHost(ip, tmp[1], senderString, "")
  146. if res == spf.None || res == spf.Pass {
  147. // spf校验通过
  148. return true
  149. }
  150. return false
  151. }