Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

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!

Help! Creating a MimeMessage from a String

843830May 9 2006 — edited May 9 2006
Hi,

I'm going crazy trying to do something quite simple. How can I create a MimeMessage object from a String? The String is simply text read in from an saved email (a text file). I can't seem to figure out how to extract information from the headers, and I also need to extract the attached JPEG from some of the saved emails.

Here is my code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.image.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class ParseIt
{
   public static void main(String args[]) 
   {
   	new ParseIt("test.email");
   }

   public ParseIt(String emailName)
   {
 	String emailString = "";
	
	//read in string from email...
	try 
	{
        	BufferedReader in = new BufferedReader(new FileReader(emailName));
        	String str;
        	while ((str = in.readLine()) != null) 
		{
			emailString += str;
        	}
        	in.close();
    	} 
	catch (IOException e) 
	{
    	}
	  
	//create MimeMessage from String...
  	try
	{
		ByteArrayInputStream bais = new ByteArrayInputStream( emailString.getBytes() );
	
		Properties props = System.getProperties();
		Session session = Session.getDefaultInstance(props, null);
		MimeMessage mm = new MimeMessage(session, bais);

		//WHY DOESN'T THIS WORK???
		System.out.println("linecount: " + mm.getLineCount());
		System.out.println("filename: " + mm.getFileName());
		System.out.println("descr: " + mm.getDescription());
		System.out.println("from: " + mm.getFrom());

		//THIS WORKS FINE...
		mm.writeTo(System.out);
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
   }
}
It's odd because I can write the MimeMessage back out (here to System.out), but it's not properly extracting the data usefully. getLineCount() returns -1, and everything else returns null!

Any help would be super helpful! I don't want to set up an actual mail server, I just want a utility to parse out certain info from multipart emails (including attached image) into a java object.

Thanks, Angus

Message was edited by:
angles
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 6 2006
Added on May 9 2006
3 comments
797 views