Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Preserve the original email and save a modified copy

See more Email Object Examples

Use with-attachments.eml as a stand-in for bytes from an IMAP fetch or a message queue. Preserve those bytes first. Parse them into an Email object, add a local processing header, and serialize the result into a separate buffer. The archived input remains suitable for later byte-level inspection.

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;

public class ChilkatExample {

    public static void main(String[] args) {
        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        BinData mimeBytes = new BinData();
        try {
            mimeBytes.loadFile("with-attachments.eml");
        } catch (ChilkatException e) {
            System.out.println("Failed: mimeBytes.LoadFile.");
            return;
        }

        try {
            mimeBytes.writeFile("received-original.eml");
        } catch (ChilkatException e) {
            System.out.println("Failed: mimeBytes.WriteFile.");
            return;
        }

        Email email = new Email();
        try {
            email.setFromMimeBd(mimeBytes);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        email.addHeaderField("X-Workflow-State", "reviewed");
        // GetMimeBd appends to its destination. Use a fresh buffer for this message.
        BinData rendered = new BinData();
        try {
            email.getMimeBd(rendered);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        try {
            rendered.writeFile("reviewed.eml");
        } catch (ChilkatException e) {
            System.out.println("Failed: rendered.WriteFile.");
            return;
        }

        System.out.println("Archived received-original.eml and saved reviewed.eml.");
    }
}