read_content.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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.To, bytes.NewReader(emailData))
  42. if s.From != "" {
  43. from := parsemail.BuilderUser(s.From)
  44. if email.From == nil {
  45. email.From = from
  46. }
  47. if email.From.EmailAddress != from.EmailAddress {
  48. // 协议中的from和邮件内容中的from不匹配,当成垃圾邮件处理
  49. //log.WithContext(s.Ctx).Infof("垃圾邮件,拒信")
  50. //return nil
  51. }
  52. }
  53. // 判断是收信还是转发
  54. account, domain := email.From.GetDomainAccount()
  55. if array.InArray(domain, config.Instance.Domains) && s.Ctx.UserName == account {
  56. // 转发
  57. err := saveEmail(ctx, email, 1, true, true)
  58. if err != nil {
  59. log.WithContext(ctx).Errorf("Email Save Error %v", err)
  60. }
  61. send.Send(ctx, email)
  62. } else {
  63. // 收件
  64. var dkimStatus, SPFStatus bool
  65. // DKIM校验
  66. dkimStatus = parsemail.Check(bytes.NewReader(emailData))
  67. if err != nil {
  68. log.WithContext(ctx).Errorf("邮件内容解析失败! Error : %v \n", err)
  69. }
  70. SPFStatus = spfCheck(s.RemoteAddress.String(), email.Sender, email.Sender.EmailAddress)
  71. saveEmail(ctx, email, 0, SPFStatus, dkimStatus)
  72. log.WithContext(ctx).Debugf("开始执行插件!")
  73. as2 := async.New(ctx)
  74. for _, hook := range hooks.HookList {
  75. if hook == nil {
  76. continue
  77. }
  78. as2.WaitProcess(func(hk any) {
  79. hk.(hooks.EmailHook).ReceiveParseAfter(email)
  80. }, hook)
  81. }
  82. as2.Wait()
  83. log.WithContext(ctx).Debugf("开始执行邮件规则!")
  84. // 执行邮件规则
  85. rs := rule.GetAllRules(ctx)
  86. for _, r := range rs {
  87. if rule.MatchRule(ctx, r, email) {
  88. rule.DoRule(ctx, r, email)
  89. }
  90. }
  91. }
  92. return nil
  93. }
  94. func saveEmail(ctx *context.Context, email *parsemail.Email, emailType int, SPFStatus, dkimStatus bool) error {
  95. var dkimV, spfV int8
  96. if dkimStatus {
  97. dkimV = 1
  98. }
  99. if SPFStatus {
  100. spfV = 1
  101. }
  102. // 垃圾过滤
  103. if config.Instance.SpamFilterLevel == 1 && !SPFStatus && !dkimStatus {
  104. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  105. return nil
  106. }
  107. if config.Instance.SpamFilterLevel == 2 && !SPFStatus {
  108. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  109. return nil
  110. }
  111. log.WithContext(ctx).Debugf("开始入库!")
  112. if email == nil {
  113. return nil
  114. }
  115. 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 (?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  116. _, err := db.Instance.Exec(sql,
  117. emailType,
  118. email.Date,
  119. email.Subject,
  120. json2string(email.ReplyTo),
  121. email.From.Name,
  122. email.From.EmailAddress,
  123. json2string(email.To),
  124. json2string(email.Bcc),
  125. json2string(email.Cc),
  126. email.Text,
  127. email.HTML,
  128. json2string(email.Sender),
  129. json2string(email.Attachments),
  130. spfV,
  131. dkimV,
  132. time.Now(),
  133. email.IsRead,
  134. email.Status,
  135. email.GroupId,
  136. )
  137. if err != nil {
  138. log.WithContext(ctx).Println("mysql insert error:", err.Error())
  139. }
  140. return nil
  141. }
  142. func json2string(d any) string {
  143. by, _ := json.Marshal(d)
  144. return string(by)
  145. }
  146. func spfCheck(remoteAddress string, sender *parsemail.User, senderString string) bool {
  147. //spf校验
  148. ipAddress, _ := netip.ParseAddrPort(remoteAddress)
  149. ip := net.ParseIP(ipAddress.Addr().String())
  150. if ip.IsPrivate() {
  151. return true
  152. }
  153. tmp := strings.Split(sender.EmailAddress, "@")
  154. if len(tmp) < 2 {
  155. return false
  156. }
  157. res := spf.CheckHost(ip, tmp[1], senderString, "")
  158. if res == spf.None || res == spf.Pass {
  159. // spf校验通过
  160. return true
  161. }
  162. return false
  163. }