read_content.go 4.6 KB

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