Search code examples
dartflutterimap

Getting all the emails into a list using IMAP


I am trying to create an mail app in Flutter, right now I am testing the back end then I want to integrate it in my app.

I am using IMAP to get all my emails from my university and insert them into a list using a class called Emails with parameters like subject, date, from, to and body (all string types).

    List emails;
  Future<EMails> getEmails() async {
    ImapFolder inbox = await client.getFolder("inbox");
    EMails list;
    for (var i = inbox.mailCount; i > 0; i--) {
      list.subject = await inbox.fetch(["BODY.PEEK[HEADER.FIELDS (SUBJECT)]"],
          messageIds: [i]) as String; //gets the subject
      list.date = await inbox.fetch(["BODY.PEEK[HEADER.FIELDS (Date)]"],
          messageIds: [i]) as String; //gets the Date
      list.from = await inbox.fetch(["BODY.PEEK[HEADER.FIELDS (From)]"],
          messageIds: [i]) as String; //gets the From
      list.to =
          await inbox.fetch(["BODY.PEEK[HEADER.FIELDS (To)]"], messageIds: [i])
              as String; //gets the To
      list.body = await inbox.fetch(["RFC822.TEXT"], messageIds: [i]) as String;
      emails.add(list);
    }
    return list;
  }

The problem is that I can't transform my fetching data into strings. https://i.sstatic.net/hY2DF.png


Solution

  • .fetch returns a Future, but it looks like you're not waiting for it yet. Add await in front of each inbox.fetch.

    This is documented at https://pub.dev/documentation/imap_client/latest/imap_client/ImapFolder-class.html