Search code examples
c#winformsemailimapchilkat

Show Email body in textbox from listbox Imap/pop3


So I have a listbox that shows the subject of an email (I use the chilkat imap client) when I select the subject of an email I want to show the message body in a textbox but i cant figure out how to do it, obviusly i use the listbox selectindexchanaged event but how would i go about it

Code So Far

// Create an object, connect to the IMAP server, login,
        // and select a mailbox.
        Chilkat.Imap imap = new Chilkat.Imap();
        imap.UnlockComponent("UnlockCode");
        imap.Connect("Imap URL");
        imap.Login("email address", "password");
        imap.SelectMailbox("Inbox");

        // Get a message set containing all the message IDs
        // in the selected mailbox.
        Chilkat.MessageSet msgSet;
        msgSet = imap.Search("ALL", true);

        // Fetch all the mail into a bundle object.
        Chilkat.EmailBundle bundle = new Chilkat.EmailBundle();
        bundle = imap.FetchBundle(msgSet);

        // Loop over the bundle and display the From and Subject.
        Chilkat.Email email;
        int i;
        for (i = 0; i < bundle.MessageCount - 1; i++)
        {

            email = bundle.GetEmail(i);
            listBox1.Items.Add(email.From + ": " + email.Subject);
            textBox1.Text = email.Body ;

        }

        // Save the email to an XML file
        bundle.SaveXml("bundle.xml");



        // Disconnect from the IMAP server.
        // This example leaves the email on the IMAP server.
        imap.Disconnect();
    }
}

thanks in advance


Solution

  • Assuming that the email indexes stay the same (I think the safest way to make sure of that would be to cache the fetched bundle in the form), I'd change to using a ListView instead of the ListBox and then I'd add the indexes to the list, either as a separate column or in the Tag of the items.

    After you'd set up the ListView to look as you need it to look (ListView.View = View.Details; and ListView.MultiSelect = false; are probably the main ones) instead of:

    listBox1.Items.Add(email.From + ": " + email.Subject);
    

    you could do something like (if you do it the Tag way, which is slightly easier but some people think is bad):

    listView1.Items.Add(email.From + ": " + email.Subject).Tag = i;
    

    And then when the user selects a subject in the list, as you say, you handle the ListView.SelectedIndexChanged event and then just do something like:

    if(ListView.SelectedItems.Count > 0)
    {
        textBox1.Text = bundle.GetEmail((int)ListView.SelectedItems[0].Tag).Body;
    }
    

    Or if you're sure you only ever want to get out the text from the emails, you could insert the texts into the tags instead of the indexes.