agamendon
agamendon

Reputation: 15

Unexpected IMAP behaviour in Go

I have following function in Go that uses emersion/go-imap library. I am calling it every minute. It is manifesting unexpected behaviour in following way:

  1. I am launching the program - nothing happens, as there are no unread messages
  2. Between initial check and second check two messages arrive - message A and message B
  3. The function correctly identifies both of them and puts them into channel; HOWEVER, bodies of both returned messages are empty.
  4. No messages arrive between second and third check. However, the function identifies message B as unread and puts it into channel again - this time, with message body included
func (f *imapMessageFetcher) searchUnreadFetchProcess() error {
    criteria := imap.SearchCriteria{
        Not: []imap.SearchCriteria{{
            Flag: []imap.Flag{imap.FlagSeen},
        }},
    }

    data, err := f.client.Search(&criteria, nil).Wait()
    if err != nil {
        return fmt.Errorf("failed to search for unread messages: %w", err)
    }

    seqNums := data.AllSeqNums()
    if len(seqNums) == 0 {
        return nil
    }
    log.Printf("found %d unread messages\n", len(seqNums))
    seqset := imap.SeqSetNum(seqNums...)

    fetchOptions := &imap.FetchOptions{
        Flags:       true,
        Envelope:    true,
        BodySection: []*imap.FetchItemBodySection{{}},
    }

    fetchCmd := f.client.Fetch(seqset, fetchOptions)
    defer func() {
        err := fetchCmd.Close()
        if err != nil {
            log.Printf("error closing fetchCmd: %d\n", err)
        }
    }()

    for {
        msgData := fetchCmd.Next()
        if msgData == nil {
            fmt.Println("no more messages to read")
            break
        }
        msgBuffer, err := msgData.Collect()
        if err != nil {
            return fmt.Errorf("error collecting message data %d: ", err)
        }
        log.Printf("finished reading message\n")
        f.outputMessages <- msgBuffer
    }
    return nil
}

As far as I understand, this is not what is supposed to happen. What might be the cause?

Upvotes: 1

Views: 47

Answers (0)

Related Questions