email.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package resource
  2. import (
  3. "errors"
  4. "github.com/emersion/go-imap"
  5. "github.com/emersion/go-imap/client"
  6. "github.com/emersion/go-message/charset"
  7. "github.com/emersion/go-message/mail"
  8. "hongze/fms_api/global"
  9. "hongze/fms_api/utils"
  10. "io"
  11. "io/ioutil"
  12. "os"
  13. "regexp"
  14. "strings"
  15. "time"
  16. )
  17. type EmailImapService struct {
  18. Client *client.Client
  19. }
  20. func NewEmailImapService() *EmailImapService {
  21. global.LOG.Info("Connecting to server...")
  22. // Connect to server
  23. //c, err := client.DialTLS("imap.qq.com:993", nil)
  24. var emailHost string
  25. if global.CONFIG.Serve.RunMode != "debug" {
  26. emailHost = "imap.qiye.aliyun.com:993"
  27. } else {
  28. //测试邮箱
  29. emailHost = "imap.aliyun.com:993"
  30. }
  31. c, err := client.DialTLS(emailHost, nil)
  32. if err != nil {
  33. panic("连接邮箱服务器失败:" + err.Error())
  34. }
  35. global.LOG.Info("Connected success")
  36. return &EmailImapService{Client: c}
  37. }
  38. type AttachmentListItem struct {
  39. Title string
  40. Date time.Time
  41. Name string
  42. Position string
  43. FullPath string
  44. FileName string
  45. FromEmails []string
  46. LoadUrl string
  47. }
  48. //DownLoadCv 下载简历附件接口
  49. func (e *EmailImapService) DownLoadEmailCv(username, password string, attachmentChan chan *AttachmentListItem) (err error) {
  50. // Don't forget to logout
  51. defer e.Client.Logout()
  52. defer close(attachmentChan)
  53. // Login
  54. if err = e.Client.Login(username, password); err != nil {
  55. global.LOG.Info("login failed err: " + err.Error())
  56. return
  57. }
  58. global.LOG.Info("login in")
  59. // Select INBOX
  60. mbox, err := e.Client.Select("INBOX", false)
  61. if err != nil {
  62. global.LOG.Error(err)
  63. return
  64. }
  65. // Get the last message
  66. if mbox.Messages == 0 {
  67. global.LOG.Error("No message in mailbox")
  68. return
  69. }
  70. /*// 筛选最近7天的邮件
  71. //criteria := imap.NewSearchCriteria()
  72. //criteria.WithoutFlags = []string{imap.SeenFlag}
  73. //criteria.SentSince = time.Date(1984, 11, 5, 0, 0, 0, 0, time.UTC)
  74. //ids, err := e.Client.Search(criteria)
  75. if err != nil {
  76. global.LOG.Error("No search message in mailbox"+err.Error())
  77. return
  78. }
  79. if len(ids) == 0 {
  80. global.LOG.Error("No search message in mailbox")
  81. return
  82. }
  83. seqSet := new(imap.SeqSet)
  84. seqSet.AddNum(ids...)*/
  85. seqSet := new(imap.SeqSet)
  86. from := uint32(1)
  87. to := mbox.Messages
  88. if mbox.Messages > 100 {
  89. // We're using unsigned integers here, only subtract if the result is > 0
  90. from = mbox.Messages - 100
  91. }
  92. seqSet.AddRange(from, to)
  93. global.LOG.Infof("mbox.Messages length :%d", mbox.Messages)
  94. // Get the whole message body
  95. var section imap.BodySectionName
  96. items := []imap.FetchItem{section.FetchItem()}
  97. messages := make(chan *imap.Message, mbox.Messages)
  98. done := make(chan error, 1)
  99. go func() {
  100. done <- e.Client.Fetch(seqSet, items, messages)
  101. }()
  102. global.LOG.Info("最近7天收到的邮件:")
  103. imap.CharsetReader = charset.Reader
  104. beforeDate7 := time.Now().AddDate(0, 0, -7)
  105. for msg := range messages {
  106. if msg == nil {
  107. err = errors.New("Server didn't returned message")
  108. global.LOG.Error("Server didn't returned message")
  109. return
  110. }
  111. tmp := new(AttachmentListItem)
  112. section = imap.BodySectionName{}
  113. r := msg.GetBody(&section)
  114. if r == nil {
  115. err = errors.New("Server didn't returned message body")
  116. global.LOG.Error("Server didn't returned message body")
  117. return
  118. }
  119. var mr *mail.Reader
  120. mr, err = mail.CreateReader(r)
  121. if err != nil {
  122. global.LOG.Error(err)
  123. return
  124. }
  125. // Print some info about the message
  126. header := mr.Header
  127. var emailDate time.Time
  128. if emailDate, err = header.Date(); err == nil {
  129. global.LOG.Infof("Date:%s", emailDate.Format(utils.FormatDateTime))
  130. if emailDate.Before(beforeDate7) {
  131. continue
  132. }
  133. //global.LOG.Infof("Date:", emailDate)
  134. tmp.Date = emailDate
  135. }
  136. if subject, err := header.Subject(); err == nil {
  137. global.LOG.Infof("Subject:%s", subject)
  138. newSubject, info, flag := DealSubject(subject)
  139. if !flag {
  140. continue
  141. }
  142. tmp.Title = newSubject
  143. tmp.Name = info.Name
  144. tmp.Position = info.Position
  145. }
  146. if from, err := header.AddressList("From"); err == nil {
  147. global.LOG.Infof("From:%s", from)
  148. //tmp.SenderEmails = from
  149. for _, fa := range from {
  150. tmp.FromEmails = append(tmp.FromEmails, fa.Address)
  151. }
  152. }
  153. if to, err := header.AddressList("To"); err == nil {
  154. global.LOG.Infof("To:%s", to)
  155. }
  156. // Process each message's part
  157. for {
  158. p, tErr := mr.NextPart()
  159. if tErr == io.EOF {
  160. break
  161. } else if tErr != nil {
  162. global.LOG.Errorf("Process each message's part err:%v", tErr)
  163. return
  164. }
  165. switch h := p.Header.(type) {
  166. case *mail.InlineHeader:
  167. // This is the message's text (can be plain-text or HTML)
  168. _, _ = ioutil.ReadAll(p.Body)
  169. //global.LOG.Infof("Got text: %v", string(b))
  170. case *mail.AttachmentHeader:
  171. // This is an attachment
  172. filename, _ := h.Filename()
  173. tmp.FileName = filename
  174. global.LOG.Infof("Got attachment: %v", filename)
  175. //保存到本地
  176. dir, tmpErr := mk_dir("download/cv/" + emailDate.Format(utils.FormatDateTimeUnSpace))
  177. if tmpErr != nil {
  178. err = tmpErr
  179. global.LOG.Infof("%v 写入失败 err %s", filename, err.Error())
  180. return
  181. }
  182. filename = dir + "/" + filename
  183. content, _ := ioutil.ReadAll(p.Body)
  184. //global.LOG.Infof("Got text: %v", string(content))
  185. err = write_to_file(filename, content)
  186. if err != nil {
  187. global.LOG.Infof("%v 写入失败", filename)
  188. return
  189. }
  190. tmp.FullPath = filename
  191. /*tmpFileName := strings.Split(path.Base(tmp.FileName), ".")
  192. tmpName := tmpFileName[0]
  193. ext := tmpFileName[1]
  194. global.LOG.Infof("Got attachment ext: %v", ext)
  195. if ext == "docx" {
  196. fileOutPath, e := FuncDocs2Pdf(global.CONFIG.Serve.LibreOfficePath, filename ,dir,"pdf")
  197. if e != nil {
  198. err = e
  199. global.LOG.Infof("docx 转pdf 失败:%v",e.Error())
  200. return
  201. }
  202. tmp.FullPath = fileOutPath
  203. tmp.FileName = tmpName + ".pdf"
  204. }*/
  205. //把结果放到channel中
  206. attachmentChan <- tmp
  207. }
  208. }
  209. }
  210. if err = <-done; err != nil {
  211. global.LOG.Info("email client Fetch Err: " + err.Error())
  212. return
  213. }
  214. return
  215. }
  216. func mk_dir(dir_path string) (string, error) {
  217. var path string
  218. if os.IsPathSeparator('\\') { //前边的判断是否是系统的分隔符
  219. path = "\\"
  220. } else {
  221. path = "/"
  222. }
  223. //fmt.Println(path)
  224. dir, _ := os.Getwd() //当前的目录
  225. err := os.MkdirAll(dir+path+dir_path, os.ModePerm) //在当前目录下生成md目录
  226. if err != nil {
  227. global.LOG.Infof("%v", err)
  228. return "", nil
  229. }
  230. return dir + path + dir_path, nil
  231. }
  232. /*
  233. 函数名称:write_to_file
  234. 函数作用:写内容到文件
  235. 输入参数:filename(文件名),content(内容)
  236. 输出参数:无
  237. */
  238. func write_to_file(filename string, content []byte) (err error) {
  239. var fileHandle *os.File
  240. /*if !checkFileIsExist(filename) { //如果文件存在
  241. fileHandle, err = os.Create(filename) //创建文件
  242. global.LOG.Infof("文件不存在")
  243. if err != nil {
  244. global.LOG.Infof("Err" + err.Error())
  245. }
  246. }else{*/
  247. fileHandle, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
  248. //global.LOG.Infof("文件存在")
  249. //}
  250. if err != nil {
  251. return
  252. }
  253. defer fileHandle.Close()
  254. //循环读取
  255. // NewWriter 默认缓冲区大小是 4096
  256. // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法
  257. // buf := bufio.NewWriter(fileHandle)
  258. // 字节写入
  259. // 字符串写入
  260. _, err = fileHandle.WriteString(string(content))
  261. if err != nil {
  262. return
  263. }
  264. return
  265. }
  266. func DealSubject(subject string) (newSubject string, person AttachmentListItem, flag bool) {
  267. if strings.Contains(subject, "转发:") || strings.Contains(subject, "Fwd:") {
  268. reg := `^[Fwd:|转发:]+`
  269. re := regexp.MustCompile(reg)
  270. subject = re.ReplaceAllString(subject, "")
  271. }
  272. newSubject = subject
  273. person, flag = dealBossSubject(subject)
  274. if !flag {
  275. person, flag = dealDefaultSubject(subject)
  276. if !flag {
  277. person, flag = dealLiePinSubject(subject)
  278. if !flag {
  279. person, flag = dealOtherSubject(subject)
  280. }
  281. }
  282. }
  283. return
  284. }
  285. func dealBossSubject(subject string) (person AttachmentListItem, flag bool) {
  286. matched, err := regexp.MatchString(`(.*)【BOSS直聘】`, subject)
  287. if err != nil {
  288. return
  289. }
  290. if !matched {
  291. return
  292. }
  293. items := strings.Split(subject, "|")
  294. if len(items) < 3 {
  295. return
  296. }
  297. name := items[0]
  298. global.LOG.Infof("求职姓名:%s", name)
  299. //获取职位
  300. items1 := strings.Split(items[1], "应聘")
  301. if len(items1) < 2 {
  302. return
  303. }
  304. position := strings.Trim(items1[1], " ")
  305. global.LOG.Infof("求职岗位:%s", position)
  306. person.Name = name
  307. person.Position = position
  308. flag = true
  309. return
  310. }
  311. func dealDefaultSubject(subject string) (person AttachmentListItem, flag bool) {
  312. reg := `[(](.*)[)-](.*){1,10}[先生|女士]$`
  313. matched, err := regexp.MatchString(reg, subject)
  314. if err != nil {
  315. return
  316. }
  317. if !matched {
  318. return
  319. }
  320. re := regexp.MustCompile(reg)
  321. position := re.ReplaceAllString(subject, "")
  322. global.LOG.Infof("求职岗位:%s", position)
  323. if position == "" {
  324. return
  325. }
  326. //获取职位
  327. items := strings.Split(subject, "-")
  328. if len(items) < 2 {
  329. return
  330. }
  331. name := items[len(items)-1]
  332. global.LOG.Infof("求职姓名:%s", name)
  333. person.Name = name
  334. person.Position = position
  335. flag = true
  336. return
  337. }
  338. func dealLiePinSubject(subject string) (person AttachmentListItem, flag bool) {
  339. reg := `来自猎聘的候选人`
  340. matched, err := regexp.MatchString(reg, subject)
  341. if err != nil {
  342. return
  343. }
  344. if !matched {
  345. return
  346. }
  347. // Regex pattern captures "key: value" pair from the content.
  348. pattern := regexp.MustCompile("【(?P<key1>(.*)+)_(?P<key2>(.*)+)】(?P<key3>(.*)+)_(?P<key4>(.*)+)")
  349. // Template to convert "key: value" to "key=value" by
  350. // referencing the values captured by the regex pattern.
  351. template := "$key1=$key2=$key3=$key4\n"
  352. result := []byte{}
  353. // For each match of the regex in the content.
  354. for _, submatches := range pattern.FindAllStringSubmatchIndex(subject, -1) {
  355. // Apply the captured submatches to the template and append the output
  356. // to the result.
  357. result = pattern.ExpandString(result, template, subject, submatches)
  358. }
  359. global.LOG.Infof("求职邮件匹配结果:%s", string(result))
  360. //获取职位
  361. tmp := strings.Split(string(result), "=")
  362. if len(tmp) < 4 {
  363. return
  364. }
  365. position := strings.Trim(tmp[0], " ")
  366. global.LOG.Infof("求职岗位:%s", position)
  367. name := strings.Trim(tmp[2], " ")
  368. global.LOG.Infof("求职姓名:%s", name)
  369. person.Name = name
  370. person.Position = position
  371. flag = true
  372. return
  373. }
  374. func dealOtherSubject(subject string) (person AttachmentListItem, flag bool) {
  375. reg := `^New application`
  376. matched, err := regexp.MatchString(reg, subject)
  377. if err != nil {
  378. return
  379. }
  380. if !matched {
  381. return
  382. }
  383. // Regex pattern captures "key: value" pair from the content.
  384. pattern := regexp.MustCompile(`(?P<key1>[a-zA-z\s]+)from(?P<key2>[a-zA-z\s]+)`)
  385. // Template to convert "key: value" to "key=value" by
  386. // referencing the values captured by the regex pattern.
  387. template := "$key1=$key2\n"
  388. result := []byte{}
  389. // For each match of the regex in the content.
  390. for _, submatches := range pattern.FindAllStringSubmatchIndex(subject, -1) {
  391. // Apply the captured submatches to the template and append the output
  392. // to the result.
  393. result = pattern.ExpandString(result, template, subject, submatches)
  394. }
  395. global.LOG.Infof("求职邮件匹配结果:%s", string(result))
  396. //获取职位
  397. tmp := strings.Split(string(result), "=")
  398. if len(tmp) < 2 {
  399. return
  400. }
  401. position := strings.Trim(tmp[0], " ")
  402. global.LOG.Infof("求职岗位:%s", position)
  403. name := strings.Trim(tmp[1], " ")
  404. global.LOG.Infof("求职姓名:%s", name)
  405. person.Name = name
  406. person.Position = position
  407. flag = true
  408. return
  409. }