修改电子邮件标题,而不在内存中加载电子邮

时间:2017-05-31 10:49:45

标签: java javamail mime-message email-parsing

我正在使用JavaMail API来解析电子邮件标头。 在电子邮件文件大小为KB的正常情况下,它不会在JVM中占用太多内存。但是,如果带有附件的大型电子邮件文件(35MB +),它会在JVM中占用大量空间。

如果没有在momory中加载电子邮件内容,是否有可能修改电子邮件标题?

我正在做这样的事情:

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 个答案:

答案 0 :(得分:0)

作为EML文件的邮件存储为文本文件。 典型的eml看起来像这样:

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 <real@rgagnon.com>; Sun, 1 Feb 2004 13:25:33 -0500 (EST)
Date: Sun, 01 Feb 2004 13:31:40 -0500
From: real gagnon <real@rgagnon.com>
Reply-To: real@rgagnon.com
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: real@rgagnon.com
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

因此,您可以阅读该文件,直到找到两个新行。

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();
        }

您可以在此处找到确切的规格

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