read_content.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. if email.MessageId > 0 {
  105. log.WithContext(ctx).Debugf("开始执行邮件规则!")
  106. // 执行邮件规则
  107. rs := rule.GetAllRules(ctx)
  108. for _, r := range rs {
  109. if rule.MatchRule(ctx, r, email) {
  110. rule.DoRule(ctx, r, email)
  111. }
  112. }
  113. }
  114. log.WithContext(ctx).Debugf("开始执行插件ReceiveSaveAfter!")
  115. as3 := async.New(ctx)
  116. for _, hook := range hooks.HookList {
  117. if hook == nil {
  118. continue
  119. }
  120. as3.WaitProcess(func(hk any) {
  121. hk.(framework.EmailHook).ReceiveSaveAfter(ctx, email)
  122. }, hook)
  123. }
  124. as3.Wait()
  125. log.WithContext(ctx).Debugf("开始执行插件ReceiveSaveAfter!End")
  126. }
  127. return nil
  128. }
  129. func saveEmail(ctx *context.Context, email *parsemail.Email, emailType int, SPFStatus, dkimStatus bool) error {
  130. var dkimV, spfV int8
  131. if dkimStatus {
  132. dkimV = 1
  133. }
  134. if SPFStatus {
  135. spfV = 1
  136. }
  137. // 垃圾过滤
  138. if config.Instance.SpamFilterLevel == 1 && !SPFStatus && !dkimStatus {
  139. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  140. return nil
  141. }
  142. if config.Instance.SpamFilterLevel == 2 && !SPFStatus {
  143. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  144. return nil
  145. }
  146. log.WithContext(ctx).Debugf("开始入库!")
  147. if email == nil {
  148. return nil
  149. }
  150. 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 (?,?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  151. res, err := db.Instance.Exec(sql,
  152. emailType,
  153. email.Date,
  154. email.Subject,
  155. json2string(email.ReplyTo),
  156. email.From.Name,
  157. email.From.EmailAddress,
  158. json2string(email.To),
  159. json2string(email.Bcc),
  160. json2string(email.Cc),
  161. email.Text,
  162. email.HTML,
  163. json2string(email.Sender),
  164. json2string(email.Attachments),
  165. spfV,
  166. dkimV,
  167. time.Now(),
  168. email.IsRead,
  169. email.Status,
  170. email.GroupId,
  171. )
  172. if err != nil {
  173. log.WithContext(ctx).Errorf("db insert error:%+v", err.Error())
  174. }
  175. insertId, _ := res.LastInsertId()
  176. if insertId > 0 {
  177. email.MessageId = insertId
  178. }
  179. return nil
  180. }
  181. func json2string(d any) string {
  182. by, _ := json.Marshal(d)
  183. return string(by)
  184. }
  185. func spfCheck(remoteAddress string, sender *parsemail.User, senderString string) bool {
  186. //spf校验
  187. ipAddress, _ := netip.ParseAddrPort(remoteAddress)
  188. ip := net.ParseIP(ipAddress.Addr().String())
  189. if ip.IsPrivate() {
  190. return true
  191. }
  192. tmp := strings.Split(sender.EmailAddress, "@")
  193. if len(tmp) < 2 {
  194. return false
  195. }
  196. res := spf.CheckHost(ip, tmp[1], senderString, "")
  197. if res == spf.None || res == spf.Pass {
  198. // spf校验通过
  199. return true
  200. }
  201. return false
  202. }