read_content.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package smtp_server
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "github.com/mileusna/spf"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/spf13/cast"
  9. "io"
  10. "net"
  11. "net/netip"
  12. "pmail/config"
  13. "pmail/db"
  14. "pmail/dto/parsemail"
  15. "pmail/hooks"
  16. "pmail/hooks/framework"
  17. "pmail/models"
  18. "pmail/services/rule"
  19. "pmail/utils/async"
  20. "pmail/utils/context"
  21. "pmail/utils/send"
  22. "strings"
  23. "time"
  24. )
  25. func (s *Session) Data(r io.Reader) error {
  26. ctx := s.Ctx
  27. log.WithContext(ctx).Debugf("收到邮件")
  28. emailData, err := io.ReadAll(r)
  29. if err != nil {
  30. log.WithContext(ctx).Error("邮件内容无法读取", err)
  31. return err
  32. }
  33. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseBefore!")
  34. for _, hook := range hooks.HookList {
  35. if hook == nil {
  36. continue
  37. }
  38. hook.ReceiveParseBefore(ctx, &emailData)
  39. }
  40. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseBefore End!")
  41. log.WithContext(ctx).Infof("邮件原始内容: %s", emailData)
  42. email := parsemail.NewEmailFromReader(s.To, bytes.NewReader(emailData))
  43. if s.From != "" {
  44. from := parsemail.BuilderUser(s.From)
  45. if email.From == nil {
  46. email.From = from
  47. }
  48. if email.From.EmailAddress != from.EmailAddress {
  49. // 协议中的from和邮件内容中的from不匹配,当成垃圾邮件处理
  50. //log.WithContext(s.Ctx).Infof("垃圾邮件,拒信")
  51. //return nil
  52. }
  53. }
  54. // 判断是收信还是转发,只要是登陆了,都当成转发处理
  55. //account, domain := email.From.GetDomainAccount()
  56. if s.Ctx.UserID > 0 {
  57. log.WithContext(ctx).Debugf("开始执行插件SendBefore!")
  58. for _, hook := range hooks.HookList {
  59. if hook == nil {
  60. continue
  61. }
  62. hook.SendBefore(ctx, email)
  63. }
  64. log.WithContext(ctx).Debugf("开始执行插件SendBefore!End")
  65. if email == nil {
  66. return nil
  67. }
  68. // 转发
  69. err := saveEmail(ctx, email, s.Ctx.UserID, 1, true, true)
  70. if err != nil {
  71. log.WithContext(ctx).Errorf("Email Save Error %v", err)
  72. }
  73. errMsg := ""
  74. err, sendErr := send.Send(ctx, email)
  75. log.WithContext(ctx).Debugf("插件执行--SendAfter")
  76. as3 := async.New(ctx)
  77. for _, hook := range hooks.HookList {
  78. if hook == nil {
  79. continue
  80. }
  81. as3.WaitProcess(func(hk any) {
  82. hk.(framework.EmailHook).SendAfter(ctx, email, sendErr)
  83. }, hook)
  84. }
  85. as3.Wait()
  86. log.WithContext(ctx).Debugf("插件执行--SendAfter")
  87. if err != nil {
  88. errMsg = err.Error()
  89. _, err := db.Instance.Exec(db.WithContext(ctx, "update email set status =2 ,error=? where id = ? "), errMsg, email.MessageId)
  90. if err != nil {
  91. log.WithContext(ctx).Errorf("sql Error :%+v", err)
  92. }
  93. } else {
  94. _, err := db.Instance.Exec(db.WithContext(ctx, "update email set status =1 where id = ? "), email.MessageId)
  95. if err != nil {
  96. log.WithContext(ctx).Errorf("sql Error :%+v", err)
  97. }
  98. }
  99. } else {
  100. // 收件
  101. var dkimStatus, SPFStatus bool
  102. // DKIM校验
  103. dkimStatus = parsemail.Check(bytes.NewReader(emailData))
  104. if err != nil {
  105. log.WithContext(ctx).Errorf("邮件内容解析失败! Error : %v \n", err)
  106. }
  107. SPFStatus = spfCheck(s.RemoteAddress.String(), email.Sender, email.Sender.EmailAddress)
  108. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseAfter!")
  109. for _, hook := range hooks.HookList {
  110. if hook == nil {
  111. continue
  112. }
  113. hook.ReceiveParseAfter(ctx, email)
  114. }
  115. log.WithContext(ctx).Debugf("开始执行插件ReceiveParseAfter!End")
  116. if email == nil {
  117. return nil
  118. }
  119. // 垃圾过滤
  120. if config.Instance.SpamFilterLevel == 1 && !SPFStatus && !dkimStatus {
  121. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  122. return nil
  123. }
  124. if config.Instance.SpamFilterLevel == 2 && !SPFStatus {
  125. log.WithContext(ctx).Infoln("垃圾邮件,拒信")
  126. return nil
  127. }
  128. saveEmail(ctx, email, 0, 0, SPFStatus, dkimStatus)
  129. if email.MessageId > 0 {
  130. log.WithContext(ctx).Debugf("开始执行邮件规则!")
  131. // 执行邮件规则
  132. rs := rule.GetAllRules(ctx)
  133. for _, r := range rs {
  134. if rule.MatchRule(ctx, r, email) {
  135. rule.DoRule(ctx, r, email)
  136. }
  137. }
  138. }
  139. log.WithContext(ctx).Debugf("开始执行插件ReceiveSaveAfter!")
  140. as3 := async.New(ctx)
  141. for _, hook := range hooks.HookList {
  142. if hook == nil {
  143. continue
  144. }
  145. as3.WaitProcess(func(hk any) {
  146. hk.(framework.EmailHook).ReceiveSaveAfter(ctx, email)
  147. }, hook)
  148. }
  149. as3.Wait()
  150. log.WithContext(ctx).Debugf("开始执行插件ReceiveSaveAfter!End")
  151. }
  152. return nil
  153. }
  154. func saveEmail(ctx *context.Context, email *parsemail.Email, sendUserID int, emailType int, SPFStatus, dkimStatus bool) error {
  155. var dkimV, spfV int8
  156. if dkimStatus {
  157. dkimV = 1
  158. }
  159. if SPFStatus {
  160. spfV = 1
  161. }
  162. log.WithContext(ctx).Debugf("开始入库!")
  163. if email == nil {
  164. return nil
  165. }
  166. modelEmail := models.Email{
  167. Type: cast.ToInt8(emailType),
  168. GroupId: email.GroupId,
  169. Subject: email.Subject,
  170. ReplyTo: json2string(email.ReplyTo),
  171. FromName: email.From.Name,
  172. FromAddress: email.From.EmailAddress,
  173. To: json2string(email.To),
  174. Bcc: json2string(email.Bcc),
  175. Cc: json2string(email.Cc),
  176. Text: sql.NullString{String: string(email.Text), Valid: true},
  177. Html: sql.NullString{String: string(email.HTML), Valid: true},
  178. Sender: json2string(email.Sender),
  179. Attachments: json2string(email.Attachments),
  180. SPFCheck: spfV,
  181. DKIMCheck: dkimV,
  182. SendUserID: sendUserID,
  183. SendDate: time.Now(),
  184. Status: cast.ToInt8(email.Status),
  185. CreateTime: time.Now(),
  186. }
  187. _, err := db.Instance.Insert(&modelEmail)
  188. if err != nil {
  189. log.WithContext(ctx).Errorf("db insert error:%+v", err.Error())
  190. }
  191. if modelEmail.Id > 0 {
  192. email.MessageId = cast.ToInt64(modelEmail.Id)
  193. }
  194. return nil
  195. }
  196. func json2string(d any) string {
  197. by, _ := json.Marshal(d)
  198. return string(by)
  199. }
  200. func spfCheck(remoteAddress string, sender *parsemail.User, senderString string) bool {
  201. //spf校验
  202. ipAddress, _ := netip.ParseAddrPort(remoteAddress)
  203. ip := net.ParseIP(ipAddress.Addr().String())
  204. if ip.IsPrivate() {
  205. return true
  206. }
  207. tmp := strings.Split(sender.EmailAddress, "@")
  208. if len(tmp) < 2 {
  209. return false
  210. }
  211. res := spf.CheckHost(ip, tmp[1], senderString, "")
  212. if res == spf.None || res == spf.Pass {
  213. // spf校验通过
  214. return true
  215. }
  216. return false
  217. }