read_content.go 4.3 KB

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