dongtang6718
2018-02-27 13:04 阅读 97
已采纳

emersion / go-imap-如何检索和列出未见消息

I'm trying to use this implementation of IMAP protocol but it seems to be impossible to retrieve unseen messages from the mailbox.

Here's my code.

package main

import (
    "emailmonitor/util"
    "fmt"
)

func main() {

    serverGmail := util.NewServerGmail()

    serverGmail.Connect()
    serverGmail.Login()
    serverGmail.ListUnseenMessages()

}

//-----------------------------------------

package util

import (
    "io/ioutil"
    "log"
    "net/mail"
    "net/smtp"

    imap "github.com/emersion/go-imap"
    "github.com/emersion/go-imap/client"
)

type ServerGmail struct {
    user    string
    pass    string
    erro    string
    cliente *client.Client
}

func NewServerGmail() *ServerGmail {
    serverGmail := &ServerGmail{}
    serverGmail.user = "xxxxxx@gmail.com"
    serverGmail.pass = "xxxxx"
    serverGmail.erro = ""

    return serverGmail
}

func (serverGmail *ServerGmail) Connect() {
    // Connect to server
    cliente, erro := client.DialTLS("smtp.gmail.com:993", nil)
    if erro != nil {
        serverGmail.erro = erro.Error()
    }
    log.Println("Connected")

    serverGmail.cliente = cliente

}

func (serverGmail *ServerGmail) Login() {
    // Login
    if erro := serverGmail.cliente.Login(serverGmail.user, serverGmail.pass); erro != nil {
        serverGmail.erro = erro.Error()
    }
    log.Println("Logged")

}

func (serverGmail *ServerGmail) setLabelBox(label string) *imap.MailboxStatus {
    mailbox, erro := serverGmail.cliente.Select(label, true)
    if erro != nil {
        serverGmail.erro = erro.Error()
    }
    return mailbox
}

func (serverGmail *ServerGmail) ListUnseenMessages() {
    mailbox := serverGmail.setLabelBox("INBOX")
    log.Println(mailbox.Unseen)
}

This line log.Println(mailbox.Unseen) prints 0 (zero) messages and as described in the docs should be "The number of unread messages". I tried with UnseenSeqNum "The sequence number of the first unseen message in the mailbox" property and also prints 0 (zero).

Its just a start but I wonder from there, how could I retrieve the unseen messages.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douzhan1868 douzhan1868 2018-02-27 13:24

    I've done this before, here an extract of my code :

    criteria := imap.NewSearchCriteria()
    criteria.WithoutFlags = []string{"\\Seen"}
    uids, err := c.Search(criteria)
    if err != nil {
        log.Println(err)
    }
    seqset := new(imap.SeqSet)
    seqset.AddNum(uids...)
    section := &imap.BodySectionName{}
    items := []imap.FetchItem{imap.FetchEnvelope, imap.FetchFlags, imap.FetchInternalDate, section.FetchItem()}
    messages := make(chan *imap.Message)
    err = c.Fetch(seqset, items, messages)
    
    点赞 评论 复制链接分享

相关推荐