Sample code for 30+ languages & platforms
Java

Fetch a Text IMAP Attachment as a String

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchAttachmentString method, which returns one text attachment decoded to a string. The first argument is the Email, the second is the zero-based attachment index, and the third is the charset used to decode the bytes. This example returns the first attachment as a UTF-8 string.

Background: This is the convenient form when you simply want a small text attachment's content inline as a string. Only use it for attachments known to be text; decoding binary content through a charset can alter or corrupt the bytes. For binary data use FetchAttachmentBd, and for large text a StringBuilder (via FetchAttachmentSb) avoids an extra copy.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.Imap;

public class ChilkatExample {

    public static void main(String[] args) {
        // Demonstrates the Imap.FetchAttachmentString method, which downloads one text attachment and
        // returns it decoded to a string.  The 1st argument is the Email, the 2nd is the zero-based
        // attachment index, and the 3rd is the charset used to decode the bytes.
        //
        // The message is fetched headers-only, then the attachment is downloaded on demand.

        Imap imap = new Imap();

        imap.setSsl(true);
        imap.setPort(993);

        try {
            imap.connect("imap.example.com");

            imap.login("user@example.com", "myPassword");

            imap.selectMailbox("Inbox");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
        // metadata describing the attachments is present, so the attachment info methods still work.
        boolean headersOnly = true;
        boolean useUid = false;
        int seqNum = 1;
        Email email = new Email();
        try {
            imap.fetchEmail(headersOnly, seqNum, useUid, email);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        int numAttach = imap.getMailNumAttach(email);
        if (numAttach > 0) {
            // FetchAttachmentString returns a string, so assign it to a string variable.
            String attachText;
            try {
                attachText = imap.fetchAttachmentString(email, 0, "utf-8");
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }

            System.out.println(attachText);
        }

        try {
            imap.disconnect();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }
    }
}