Modify email headers without loading email content in memory

539 Views Asked by At

I am using JavaMail API for parsing email headers. In normal scenario with email file size in KBs, it wont eat much memory in JVM. But, in case of large email file (35MB+) with attachments, it use huge space in JVM.

Is there any possible way for email header modification without loading email content in momory?

I am doing something like this:

Properties props = System.getProperties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream(emlFile);
MimeMessage message = new MimeMessage(mailSession, source);

message.addHeader("X-Header","HeaderValue1");
message.addHeader("Y-Header", "HeaderValue2");
message.saveChanges();
Enumeration headerschange = message.getAllHeaders();

StringBuilder headerString = new StringBuilder();
while (headerschange.hasMoreElements()) {
      Header h = (Header) headerschange.nextElement();
      headerString = headerString.append(h.getName() + ": " + h.getValue() + "\n");
}
System.out.println("headerString::::::::::::::::::::"+headerString.toString());
1

There are 1 best solutions below

2
On

Mails as EML Files are stored as text files. A typical eml looks like this :

X-Mozilla-Status: 0001
X-Mozilla-Status2: 00000000
Received: from tomts25-srv.bellnexxia.net
        (tomts25.bellnexxia.net [209.226.175.188])
    by tactika.com (8.9.3/8.9.3) with ESMTP id NAA07621
    for <[email protected]>; Sun, 1 Feb 2004 13:25:33 -0500 (EST)
Date: Sun, 01 Feb 2004 13:31:40 -0500
From: real gagnon <[email protected]>
Reply-To: [email protected]
User-Agent: Mozilla/5.0
   (Windows; U; Windows NT 5.1; en-US; rv:1.4)
   Gecko/20030624 Netscape/7.1 (ax)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: [email protected]
Subject: Example for HowTo
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit
X-UIDL: oP#!!c]^!!1;-!!T@1"!


This is an example

So you can read the file until two new lines found.

try {
            BufferedReader reader = new BufferedReader(new FileReader(new File("C:\\test\\test.eml"))); 

            StringBuilder headerString = new StringBuilder();
            String line;
            int newLines = 0;
            while((line = reader.readLine()) != null) {
                if(line.equals("\n")) {
                    newLines++;
                    if (newLines == 2) {
                        //Body starts here
                        break;
                    }
                } else {
                    headerString.append(line).append("\n");
                }
            }
            System.out.println("headerString::::::::::::::::::::"+headerString.toString());
            reader.close();
        } catch(IOException e) {
            e.printStackTrace();
        }

You find the exact specification here

http://www.ietf.org/rfc/rfc0822.txt