Ejemplo n.º 1
0
// loadMessages will search and fetch message body
func loadMessages(client *imap.Client, config *Config) error {
	cmd, err := imap.Wait(client.UIDSearch("FROM", client.Quote(config.From), "UNSEEN"))
	if err != nil {
		return err
	}

	seq := new(imap.SeqSet)

	if len(cmd.Data) > 0 {
		seq.AddNum(cmd.Data[0].SearchResults()...)
	}

	if seq.Empty() {
		return nil
	}

	logger.Infof("Fetched UIDs %v", seq)

	cmd, err = imap.Wait(client.UIDFetch(seq, "FLAGS", "INTERNALDATE", "RFC822.SIZE", "BODY[]"))
	if err != nil {
		return err
	}

	for _, rsp := range cmd.Data {
		body, err := fetchMessage(client, rsp.MessageInfo().UID)

		if err != nil {
			logger.Fatal(err)
			return err
		}

		err = writeFileFromBody(bytes.NewReader(body), config)

		if err != nil {
			logger.Fatal(err)
			return err
		}
	}

	if !seq.Empty() {
		_, err = imap.Wait(client.UIDStore(seq, "+FLAGS.SILENT", imap.NewFlagSet(`\Seen`)))
	}

	cmd.Data = nil

	return err
}