Sample code for 30+ languages & platforms
Go

Fetch a MessageSet into an EmailBundle

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchMsgSet method, which downloads the messages identified by a MessageSet and appends them to an EmailBundle. The arguments are headersOnly, the MessageSet, and the EmailBundle (which is not cleared). This example searches for unseen messages and downloads the whole set.

Background: This is the natural pairing with QueryMbx: search to get a MessageSet of matching identifiers, then download exactly those messages in one call. Fetching a set is far more efficient than looping one message at a time, and it returns an EmailBundle you iterate with MessageCount and EmailAt. Pass headersOnly = true to pull just headers for a fast preview list.

Chilkat Go Downloads

Go
    success := false

    //  Demonstrates the Imap.FetchMsgSet method, which downloads the messages identified by a
    //  MessageSet and appends them to an EmailBundle.  The 1st argument is headersOnly, the 2nd
    //  is the MessageSet, and the 3rd is the EmailBundle (which is not cleared).

    imap := chilkat.NewImap()

    imap.SetSsl(true)
    imap.SetPort(993)

    success = imap.Connect("imap.example.com")
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        return
    }

    success = imap.Login("user@example.com","myPassword")
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        return
    }

    success = imap.SelectMailbox("Inbox")
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        return
    }

    //  Find the messages to download (here, the unseen messages by UID).
    msgSet := chilkat.NewMessageSet()
    success = imap.QueryMbx("UNSEEN",true,msgSet)
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        msgSet.DisposeMessageSet()
        return
    }

    //  Download the messages in the set (full bodies) into a bundle.
    bundle := chilkat.NewEmailBundle()
    success = imap.FetchMsgSet(false,msgSet,bundle)
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        msgSet.DisposeMessageSet()
        bundle.DisposeEmailBundle()
        return
    }

    n := bundle.MessageCount()
    fmt.Println("Fetched ", n, " messages.")
    email := chilkat.NewEmail()
    var i int
    for i = 0; i <= n - 1; i++ {
        success = bundle.EmailAt(i,email)
        fmt.Println(email.Subject())
    }

    success = imap.Disconnect()
    if success == false {
        fmt.Println(imap.LastErrorText())
        imap.DisposeImap()
        msgSet.DisposeMessageSet()
        bundle.DisposeEmailBundle()
        email.DisposeEmail()
        return
    }


    imap.DisposeImap()
    msgSet.DisposeMessageSet()
    bundle.DisposeEmailBundle()
    email.DisposeEmail()