read_content.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. log.WithContext(ctx).Debugf("开始执行插件SendBefore!")
  59. as2 := async.New(ctx)
  60. for _, hook := range hooks.HookList {
  61. if hook == nil {
  62. continue
  63. }
  64. as2.WaitProcess(func(hk any) {
  65. hk.(framework.EmailHook).SendBefore(ctx, email)
  66. }, hook)
  67. }
  68. as2.Wait()
  69. log.WithContext(ctx).Debugf("开始执行插件SendBefore!End")
  70. if email == nil {
  71. return nil
  72. }
  73. // 转发
  74. err := saveEmail(ctx, email, 1, true, true)
  75. if err != nil {
  76. log.WithContext(ctx).Errorf("Email Save Error %v", err)
  77. }
  78. send.Send(ctx, email)
  79. } else {
  80. // 收件
  81. var dkimStatus, SPFStatus bool
  82. // DKIM校验
  83. dkimStatus = parsemail.Check(bytes.NewReader(emailData))
  84. if err != nil {
  85. log.WithContext(ctx).Errorf("邮件内容解析失败! Error : %v \n", err)
  86. }
  87. SPFStatus = spfCheck(s.RemoteAddress.String(), email.Sender, email.Sender.EmailAddress)
  88. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseAfter!")
  89. as2 := async.New(ctx)
  90. for _, hook := range hooks.HookList {
  91. if hook == nil {
  92. continue
  93. }
  94. as2.WaitProcess(func(hk any) {
  95. hk.(framework.EmailHook).ReceiveParseAfter(ctx, email)
  96. }, hook)
  97. }
  98. as2.Wait()
  99. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseAfter!End")
  100. if email == nil {
  101. return nil
  102. }
  103. saveEmail(ctx, email, 0, SPFStatus, dkimStatus)
  104. log.WithContext(ctx).Debugf("开始执行邮件规则!")
  105. // 执行邮件规则
  106. rs := rule.GetAllRules(ctx)
  107. for _, r := range rs {
  108. if rule.MatchRule(ctx, r, email) {
  109. rule.DoRule(ctx, r, email)
  110. }
  111. }
  112. }
  113. return nil
  114. }
  115. func saveEmail(ctx *context.Context, email *parsemail.Email, emailType int, SPFStatus, dkimStatus bool) error {
  116. var dkimV, spfV int8
  117. if dkimStatus {
  118. dkimV = 1
  119. }
  120. if SPFStatus {
  121. spfV = 1
  122. }
  123. // 垃圾过滤
  124. if config.Instance.SpamFilterLevel == 1 && !SPFStatus && !dkimStatus {
  125. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  126. return nil
  127. }
  128. if config.Instance.SpamFilterLevel == 2 && !SPFStatus {
  129. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  130. return nil
  131. }
  132. log.WithContext(ctx).Debugf("开始入库!")
  133. if email == nil {
  134. return nil
  135. }
  136. 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 (?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  137. res, err := db.Instance.Exec(sql,
  138. emailType,
  139. email.Date,
  140. email.Subject,
  141. json2string(email.ReplyTo),
  142. email.From.Name,
  143. email.From.EmailAddress,
  144. json2string(email.To),
  145. json2string(email.Bcc),
  146. json2string(email.Cc),
  147. email.Text,
  148. email.HTML,
  149. json2string(email.Sender),
  150. json2string(email.Attachments),
  151. spfV,
  152. dkimV,
  153. time.Now(),
  154. email.IsRead,
  155. email.Status,
  156. email.GroupId,
  157. )
  158. if err != nil {
  159. log.WithContext(ctx).Println("mysql insert error:", err.Error())
  160. }
  161. insertId, _ := res.LastInsertId()
  162. if insertId > 0 {
  163. email.MessageId = insertId
  164. }
  165. return nil
  166. }
  167. func json2string(d any) string {
  168. by, _ := json.Marshal(d)
  169. return string(by)
  170. }
  171. func spfCheck(remoteAddress string, sender *parsemail.User, senderString string) bool {
  172. //spf校验
  173. ipAddress, _ := netip.ParseAddrPort(remoteAddress)
  174. ip := net.ParseIP(ipAddress.Addr().String())
  175. if ip.IsPrivate() {
  176. return true
  177. }
  178. tmp := strings.Split(sender.EmailAddress, "@")
  179. if len(tmp) < 2 {
  180. return false
  181. }
  182. res := spf.CheckHost(ip, tmp[1], senderString, "")
  183. if res == spf.None || res == spf.Pass {
  184. // spf校验通过
  185. return true
  186. }
  187. return false
  188. }