email.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. package resource
  2. import (
  3. "fmt"
  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/hrms_api/global"
  9. "hongze/hrms_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() (es *EmailImapService, err error){
  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. err = fmt.Errorf("连接阿里云邮箱服务器失败:%v", err)
  34. return
  35. }
  36. global.LOG.Info("Connected success")
  37. es = &EmailImapService{Client: c}
  38. return
  39. }
  40. type AttachmentListItem struct {
  41. Title string
  42. Date time.Time
  43. Name string
  44. Position string
  45. FullPath string
  46. FileName string
  47. FromEmails []string
  48. LoadUrl string
  49. }
  50. //DownLoadCv 下载简历附件接口
  51. func (e *EmailImapService) DownLoadEmailCv(username, password string, attachmentChan chan *AttachmentListItem) (err error){
  52. // Don't forget to logout
  53. defer e.Client.Logout()
  54. defer close(attachmentChan)
  55. // Login
  56. if err = e.Client.Login(username, password); err != nil {
  57. err = fmt.Errorf("login failed err: %v", err)
  58. return
  59. }
  60. global.LOG.Info("login in")
  61. // Select INBOX
  62. mbox, err := e.Client.Select("INBOX", false)
  63. if err != nil {
  64. err = fmt.Errorf("select INBOX failed err: %v", err)
  65. return
  66. }
  67. // Get the last message
  68. if mbox.Messages == 0 {
  69. global.LOG.Info("No message in mailbox")
  70. return
  71. }
  72. global.LOG.Info("Flags for INBOX:", mbox.Flags)
  73. /*// 筛选最近7天的邮件
  74. //criteria := imap.NewSearchCriteria()
  75. //criteria.WithoutFlags = []string{imap.SeenFlag}
  76. //criteria.SentSince = time.Date(1984, 11, 5, 0, 0, 0, 0, time.UTC)
  77. //ids, err := e.Client.Search(criteria)
  78. if err != nil {
  79. global.LOG.Error("No search message in mailbox"+err.Error())
  80. return
  81. }
  82. if len(ids) == 0 {
  83. global.LOG.Error("No search message in mailbox")
  84. return
  85. }
  86. seqSet := new(imap.SeqSet)
  87. seqSet.AddNum(ids...)*/
  88. seqSet := new(imap.SeqSet)
  89. from := uint32(1)
  90. to := mbox.Messages
  91. if mbox.Messages > 20 {
  92. // We're using unsigned integers here, only subtract if the result is > 0
  93. from = mbox.Messages - 20
  94. }
  95. seqSet.AddRange(from, to)
  96. global.LOG.Infof("mbox.Messages length :%d", mbox.Messages)
  97. // Get the whole message body
  98. var section imap.BodySectionName
  99. items := []imap.FetchItem{section.FetchItem()}
  100. messages := make(chan *imap.Message, mbox.Messages)
  101. done := make(chan error, 1)
  102. go func() {
  103. done <- e.Client.Fetch(seqSet, items, messages)
  104. }()
  105. global.LOG.Info("最近7天收到的邮件:")
  106. imap.CharsetReader = charset.Reader
  107. beforeDate7 := time.Now().AddDate(0, 0, -7)
  108. for msg := range messages {
  109. if msg == nil {
  110. err = fmt.Errorf("server didn't returned message")
  111. return
  112. }
  113. tmp := new(AttachmentListItem)
  114. section = imap.BodySectionName{}
  115. r := msg.GetBody(&section)
  116. if r == nil {
  117. err = fmt.Errorf("server didn't returned message body")
  118. return
  119. }
  120. var mr *mail.Reader
  121. mr, err = mail.CreateReader(r)
  122. if err != nil {
  123. err = fmt.Errorf("mail.CreateReader err %v", err)
  124. return
  125. }
  126. // Print some info about the message
  127. header := mr.Header
  128. var emailDate time.Time
  129. if emailDate, err = header.Date(); err == nil {
  130. global.LOG.Infof("Date:%s", emailDate.Format(utils.FormatDateTime))
  131. if emailDate.Before(beforeDate7) {
  132. continue
  133. }
  134. //global.LOG.Infof("Date:", emailDate)
  135. tmp.Date = emailDate
  136. }
  137. if subject, err := header.Subject(); err == nil {
  138. global.LOG.Infof("Subject:%s", subject)
  139. newSubject, info, flag := DealSubject(subject)
  140. if !flag {
  141. continue
  142. }
  143. tmp.Title = newSubject
  144. tmp.Name = info.Name
  145. tmp.Position = info.Position
  146. }
  147. if from, err := header.AddressList("From"); err == nil {
  148. global.LOG.Infof("From:%s", from)
  149. //tmp.SenderEmails = from
  150. for _, fa := range from {
  151. tmp.FromEmails = append(tmp.FromEmails, fa.Address)
  152. }
  153. }
  154. if to, err := header.AddressList("To"); err == nil {
  155. global.LOG.Infof("To:%s", to)
  156. }
  157. // Process each message's part
  158. for {
  159. p, tErr := mr.NextPart()
  160. if tErr == io.EOF {
  161. break
  162. } else if tErr != nil {
  163. err = fmt.Errorf("process each message's part err:%v", tErr)
  164. return
  165. }
  166. switch h := p.Header.(type) {
  167. case *mail.InlineHeader:
  168. // This is the message's text (can be plain-text or HTML)
  169. _, _ = ioutil.ReadAll(p.Body)
  170. //global.LOG.Infof("Got text: %v", string(b))
  171. case *mail.AttachmentHeader:
  172. // This is an attachment
  173. filename, _ := h.Filename()
  174. tmp.FileName = filename
  175. global.LOG.Infof("Got attachment: %v", filename)
  176. //保存到本地
  177. dir, tmpErr := mk_dir("download/cv/"+emailDate.Format(utils.FormatDateTimeUnSpace))
  178. if tmpErr != nil {
  179. err = fmt.Errorf("%v 创建文件夹 err %v", filename, tmpErr)
  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. err = fmt.Errorf("%v 创建文件夹 err %v", filename, err)
  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. err = fmt.Errorf("email client fetch err %v ", err)
  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. }