1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package mail
- import (
- "errors"
- "eta/eta_email_analysis/global"
- "fmt"
- "github.com/emersion/go-imap"
- "github.com/emersion/go-imap/client"
- "github.com/emersion/go-message/mail"
- "log"
- "strings"
- )
- func ListenMailV2(c *client.Client, index int) (fromAddress, fromName string, err error) { // 收件箱
- // 创建一个序列集,用于批量读取邮件
- seqSet := new(imap.SeqSet)
- seqSet.AddRange(uint32(index), uint32(index)) // 添加指定范围内的邮件编号
- // 获取整个消息正文
- // imap.FetchEnvelope:请求获取邮件的信封数据(例如发件人、收件人、主题等元数据)。
- // imap.FetchRFC822:请求获取完整的邮件内容,包括所有头部和正文。
- items := []imap.FetchItem{imap.FetchFlags, imap.FetchEnvelope, imap.FetchRFC822}
- // 获取邮件内容 Start
- messages := make(chan *imap.Message, 5) // 创建一个通道,用于接收邮件消息
- fetchDone := make(chan error, 1) // 创建一个通道,用于接收错误消息
- go func() {
- // Fetch方法用于从服务器获取邮件数据,这里请求了邮件的信封和完整内容
- fetchDone <- c.Fetch(seqSet, items, messages)
- }()
- err = <-fetchDone
- if err != nil {
- global.LOG.Errorf("获取邮件信息出现错误:%v \n", err)
- return
- }
- // 获取邮件内容 End
- //log.Println("开始读取邮件内容")
- for msg := range messages {
- return readEveryMsgV2(msg)
- }
- return
- }
- // document link: https://github.com/emersion/go-imap/wiki/Fetching-messages
- func readEveryMsgV2(msg *imap.Message) (fromAddress, fromName string, err error) {
- // 获取邮件正文
- r := msg.GetBody(&imap.BodySectionName{})
- if r == nil {
- global.FILE_LOG.Info("服务器没有返回消息内容")
- }
- mr, err := mail.CreateReader(r)
- if err != nil {
- //log.Fatalf("邮件读取时出现错误: %v \n", err)
- err = errors.New(fmt.Sprintf("邮件读取时出现错误:%v \n", err))
- return
- }
- // 发件人
- {
- fromStr := mr.Header.Get("From")
- //fmt.Println(fromStr)
- // 处理无效地址的情况
- if !strings.Contains(fromStr, "@") {
- fromStr = strings.TrimSpace(fromStr)
- fromStr = strings.TrimPrefix(fromStr, `"`)
- fromStr = strings.TrimSuffix(fromStr, `"`)
- //fmt.Println(fromStr)
- fromAddress = fromStr
- fromName = fromStr
- } else {
- from, tmpErr := mr.Header.AddressList("From")
- if tmpErr != nil {
- log.Println("发件人 异常:", err.Error())
- }
- if len(from) > 0 {
- fromAddress = from[0].Address
- fromName = from[0].Name
- //mailMessage.From = from[0].String()
- //log.Println("发件人 From:", from)
- }
- }
- }
- return
- }
|