Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

File attachment issue in MimeMessage [Mail API]

838492Feb 10 2011 — edited Feb 14 2011
Hi,
I tried to attach PDF and XML file in MIME Message of MAIL API. I want attach encoded PDF and XML file with gzip format.
I’m able to attached both the files but its not attached properly and when i tried to retrieved back from MIME Message, I’m getting error.
Error is
--------------------------------------
java.util.zip.ZipException: oversubscribed literal/length tree
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:147)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:92)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at com.asite.supernova.test.CreateReadMimeMessage.ReadMail1(CreateReadMimeMessage.java:145)
at com.asite.supernova.test.CreateReadMimeMessage.main(CreateReadMimeMessage.java:48)
--------------------------------------
Here my code
--------------------------------------
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.codec.binary.Base64;

import com.sun.istack.internal.ByteArrayDataSource;

public class CreateReadMimeMessage {
	public static void main(String[] args) {
		CreateMail();
		ReadMail1();
	}
	
	public static void CreateMail(){
		try{
			Properties properties = System.getProperties();
	        Session session = Session.getDefaultInstance(properties);
	        
	        Message msg = new MimeMessage(session);
	        
	        msg.setSentDate(new Date());	        
	        Multipart multipart = new MimeMultipart();
	        
	        BodyPart part1 = new MimeBodyPart();	       
	        part1.setFileName("test.pdf");	        	              
	        part1.setHeader("Content-Type", "application/pdf");
	        part1.setHeader("Content-Encoding", "gzip");
	        part1.setHeader("Content-ID", "PDF");
	        
	        
	        //1
	        compressFile("test.pdf","testpdf.gzip");
	        String encodedData = new String(getBytesFromFile(new File("testpdf.gzip")));
	        //1
	        
	        DataSource ds = new ByteArrayDataSource(encodedData.getBytes(), "application/pdf");	        
	        DataHandler dh = new DataHandler(ds);
	        part1.setDataHandler(dh);
	        //part1.setText("This is only text data");
	        	        
	        BodyPart part2 = new MimeBodyPart();
	        part2.setFileName("test.xml");
	        part2.setHeader("Content-Type", "application/xml;");
	        part2.setHeader("Content-Encoding", "gzip");
	        part2.setHeader("Content-ID", "XML");
	        part2.setHeader("Content-Transfer-Encoding", "base64");
	        
	        //1
	        compressFile("test.xml","textxml.gzip");
	        String dataXML = new String(getBytesFromFile(new File("textxml.gzip")));
	        	      
	        
	        DataSource ds1 = new ByteArrayDataSource(dataXML.getBytes(), "application/xml");
	        DataHandler dh1 = new DataHandler(ds1);
	        part2.setDataHandler(dh1);	        
	        multipart.addBodyPart(part1);
	        multipart.addBodyPart(part2);
	        
	        msg.setContent(multipart);
	        
	        msg.writeTo(new FileOutputStream(new File("MIMEMessage.xml")));
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	public static void ReadMail1(){
		try{
			Properties properties = System.getProperties();
	        Session session = Session.getDefaultInstance(properties);
	        InputStream inFile = new FileInputStream(new File("MIMEMessage.xml"));
	        Message msg = new MimeMessage(session,inFile);	
	        
            Multipart multipart = (Multipart) msg.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {               
                BodyPart bodyPart = multipart.getBodyPart(i);
                
                Enumeration enumHeader = bodyPart.getAllHeaders();
                String fileExt="";
                while(enumHeader.hasMoreElements()){
                
                	Header header = (Header) enumHeader.nextElement();
                	System.out.println(header.getName() + ":" + header.getValue());
                	if(header.getName().equalsIgnoreCase("Content-ID")){
	                	if(header.getValue().equalsIgnoreCase("pdf")){
	                		fileExt=".pdf";
	                	}else if(header.getValue().equalsIgnoreCase("xml")){
	                		fileExt=".xml";
	                	}
                	}
                }
                
                BufferedInputStream inn = new BufferedInputStream(bodyPart.getInputStream());
                GZIPInputStream gzin = new GZIPInputStream(inn);
                
               
                /*****/
                // Open the output file
    			String target ="File"+i+fileExt;
    			OutputStream outf = new FileOutputStream(target);

    			// Transfer bytes from the compressed file to the output file
    			byte[] buff = new byte[128];
    			int lent;
    			while ((lent = gzin.read(buff)) > 0) {
    				outf.write(buff, 0, lent);
    			}
    			/******/               
             
            }
            
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	public static void compressFile(String input,String output) {
		try {
			// Create the GZIP output stream			 
			OutputStream out = new GZIPOutputStream(new FileOutputStream(output));
			out =new BufferedOutputStream(out);
			// Open the input file
		
			//FileInputStream in = new FileInputStream(input);
			InputStream in = new BufferedInputStream(new FileInputStream(input));

			// Transfer bytes from the input file to the GZIP output stream
			
			byte[] buf = new byte[524288];
			/*int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}*/
			
			
			int count;
			while((count = in.read(buf, 0, 524288)) != -1) {
				System.out.println(new String(buf, 0, count));
				out.write(buf, 0, count);
            }
			out.flush();
			in.close();

			// Complete the GZIP file
			//out.finish();
			out.close();			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
        System.out.println("File Len : " + length);
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
        System.out.println("offset : " + offset);
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}
Please help me asap.

Edited by: sabre150 on 10-Feb-2011 01:50

Moderator action : added [ code] tags to make the code readable.
This post has been answered by sabre150 on Feb 10 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 14 2011
Added on Feb 10 2011
3 comments
1,724 views