Sample code for 30+ languages & platforms
CkJava 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 CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkBinData mimeBytes = new CkBinData();
    success = mimeBytes.LoadFile("with-attachments.eml");
    if (success != true) {
        System.out.println("Failed: mimeBytes.LoadFile.");
        return;
        }

    success = mimeBytes.WriteFile("received-original.eml");
    if (success != true) {
        System.out.println("Failed: mimeBytes.WriteFile.");
        return;
        }

    CkEmail email = new CkEmail();
    success = email.SetFromMimeBd(mimeBytes);
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    email.AddHeaderField("X-Workflow-State","reviewed");
    //  GetMimeBd appends to its destination. Use a fresh buffer for this message.
    CkBinData rendered = new CkBinData();
    success = email.GetMimeBd(rendered);
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    success = rendered.WriteFile("reviewed.eml");
    if (success != true) {
        System.out.println("Failed: rendered.WriteFile.");
        return;
        }

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