go 读取邮件

程序读取文件


import (
	"fmt"
	"io"
	"io/ioutil"
	"regexp"
	"strings"
	"testing"
	"time"

	"github.com/emersion/go-imap"
	id "github.com/emersion/go-imap-id"
	"github.com/emersion/go-message/mail"
	"github.com/golang-module/carbon"
	"github.com/emersion/go-imap/client"
	_ "github.com/emersion/go-message/charset"
	"github.com/emersion/go-message/mail"
)
func TestReceive1(t *testing.T) {

	err, result := emailListByUid1("邮箱对应的访问权限地址", "邮箱账号", "key不是password")
	fmt.Println(err)
	// 正则表达式解析
	for _, value := range result {
		fmt.Prientln(value)
	}
}

func emailListByUid1(Eserver, UserName, Password string) (err error, result []string) {
	c, err := loginEmail(Eserver, UserName, Password)
	if err != nil {
		fmt.Println(err)
		return
	}
	idClient := id.NewClient(c)
	idClient.ID(
		id.ID{
			id.FieldName:    "IMAPClient",
			id.FieldVersion: "2.1.0",
		},
	)

	defer c.Close()

	mailboxes := make(chan *imap.MailboxInfo, 10)
	mailboxeDone := make(chan error, 1)
	go func() {
		mailboxeDone <- c.List("", "*", mailboxes)
	}()
	for box := range mailboxes {
		if box.Name != "INBOX" {
			continue
		}
		fmt.Println("切换目录:", box.Name)
		mbox, err := c.Select(box.Name, false)
		// 选择收件箱
		if err != nil {
			fmt.Println("select inbox err: ", err)
			continue
		}
		if mbox.Messages == 0 {
			continue
		}

		// 选择收取邮件的时间段
		criteria := imap.NewSearchCriteria()
		// 收取7天之内的邮件
		location, _ := time.LoadLocation(carbon.Shanghai)
		format := time.Now().Format(carbon.DateTimeFormat)
		inLocation, _ := time.ParseInLocation(carbon.DateTimeFormat, format, location)
		criteria.Since = inLocation.Add(-1 * time.Minute * 15)
		fmt.Println(criteria.Since.Unix())
		// 按条件查询邮件
		ids, err := c.UidSearch(criteria)
		fmt.Println(len(ids))
		if err != nil {
			continue
		}
		if len(ids) == 0 {
			continue
		}
		seqset := new(imap.SeqSet)
		seqset.AddNum(ids...)
		sect := &imap.BodySectionName{Peek: true}

		messages := make(chan *imap.Message, 100)
		messageDone := make(chan error, 1)

		go func() {
			messageDone <- c.UidFetch(seqset, []imap.FetchItem{sect.FetchItem()}, messages)
		}()
		for msg := range messages {
			r := msg.GetBody(sect)
			mr, err := mail.CreateReader(r)
			if err != nil {
				fmt.Println(err)
				continue
			}
			/*header := mr.Header
			fmt.Println(header.Subject())*/
			_, fileName, results := parseEmail1(mr)
			result = append(result, results...)
			for k, _ := range fileName {
				fmt.Println("收取到附件:", k)
			}
		}
	}
	return
}

func parseEmail1(mr *mail.Reader) (body []byte, fileMap map[string][]byte, results []string) {
	for {
		p, err := mr.NextPart()
		if err == io.EOF {
			break
		} else if err != nil {
			break
		}
		if p != nil {
			switch p.Header.(type) {
			case *mail.InlineHeader:
				body, err = ioutil.ReadAll(p.Body)
				if err != nil {
					fmt.Println("read body err:", err.Error())
				}
				//fmt.Println(string(body))
				//fmt.Println("---------------------------------------------------------")
				results = append(results, string(body))

				/*case *mail.AttachmentHeader:
				fileName, _ := h.Filename()
				fileContent, _ := ioutil.ReadAll(p.Body)
				fileMap[fileName] = fileContent*/
			}
		}
	}
	return
}

func loginEmail(Eserver, UserName, Password string) (*client.Client, error) {
	dial := new(net.Dialer)
	dial.Timeout = time.Duration(3) * time.Second
	c, err := client.DialWithDialerTLS(dial, Eserver, nil)
	if err != nil {
		c, err = client.DialWithDialer(dial, Eserver) // 非加密登录
	}
	if err != nil {
		return nil, err
	}
	// 登陆
	if err = c.Login(UserName, Password); err != nil {
		return nil, err
	}
	return c, nil
}
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值