Link to home
Start Free TrialLog in
Avatar of harmeek_80
harmeek_80

asked on

Receiving text/html in mail thru JavaMail API

Hi Friends,
I am following the JavaMail APi and I want to send an image in my mail.I am able to send the mail,and view the image thru outlook exprees.But when i try to view the image using my code....i get only the bytecodes of the image in my command promt.Here's my code..please help.

public class ReceiveMail extends JFrame
{
       public static void main (String args[]) throws Exception {
 
             String host = "pop.broadband.rogers.com";
             String username = "xyz@rogers.com";              
             String password = "*****";  
             Properties props = new Properties();

         Session session = Session.getDefaultInstance(props, null);

         Store store = session.getStore("pop3");
         store.connect(host, username, password);
         Folder folder = store.getFolder("INBOX");
         folder.open(Folder.READ_ONLY);
       
         BufferedReader reader = new BufferedReader (
         new InputStreamReader(System.in));

          // Get directory                
         Message message[] = folder.getMessages();
             for (int i=0, n=message.length; i<n; i++) {
               System.out.println(i + ": " + message[i].getFrom()[0]
                 + "\t" + message[i].getSubject());



         System.out.println("Do you want to read message? " +
               "[YES to read/QUIT to end]");
             String line = reader.readLine();
             if ("YES".equals(line)) {
                   
                   if (message[i].getContentType().equals("text/html"))
                   {
                   String content = (String)message[i].getContent();
            JFrame frame = new JFrame();
            JEditorPane text = new JEditorPane("text/html", content);
            text.setEditable(false);
            JScrollPane pane = new JScrollPane(text);
            frame.getContentPane().add(pane);
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.show();
            }                   
             message[i].writeTo(System.out);
              } else if ("QUIT".equals(line)) {
                break;
              }
      }



folder.close(false);
store.close();
}
}
Avatar of aozarov
aozarov

For sending image attachment check: http://java.sun.com/developer/EJTechTips/2004/tt0625.html
For receiving : http://java.sun.com/developer/onlineTraining/JavaMail/contents.html (search "Getting Attachments")
Avatar of harmeek_80

ASKER

Thanks aozarov yet again,
I am already following the second link to learn javamail api.....anyways the first link looks gud..let me go thru it.and then i wud return to hand over the points to you  as usual.
Hi Aozarov,
I went thru the first example you gave me..but thats not what i need.It tells you how to send an email..but as i wrote earlier..i am able to send an email...but i am not able to recieve the images ..i get bytecode in return.Can you or  someone else please tell me how to accomplish this??
From the section: http://java.sun.com/developer/onlineTraining/JavaMail/contents.html (search "Getting Attachments")
With some additions.

Multipart mp = (Multipart)message.getContent();

for (int i=0, n=multipart.getCount(); i<n; i++) {
  Part part = multipart.getBodyPart(i));

  String disposition = part.getDisposition();
if (disposition == null) {
  // Check if plain
  MimeBodyPart mbp = (MimeBodyPart)part;
  if (mbp.isMimeType("text/plain")) {
    // Handle plain
  } else {
    // Special non-attachment cases here of
    // image/gif, text/html, ...
    if (mbp.isMimeType("image/gif")) {
        // here you can call part.getInputStream()
        // and write all to a ByteArrayOutputStream instance
        // then call toByteArray() to get byte array from the ByteArrayOutputStream
       // then you can use Toolkit.getDefaultToolkit().createImage(with the byte array)
       // or ImageIcon(with the byte array)
       // and can create a label with that image
     }
  }
...
}
Thanks Aozarov,
Can you please throw in some code or link for this part:


if (mbp.isMimeType("image/gif")) {
        // here you can call part.getInputStream()
        // and write all to a ByteArrayOutputStream instance
        // then call toByteArray() to get byte array from the ByteArrayOutputStream
       // then you can use Toolkit.getDefaultToolkit().createImage(with the byte array)
       // or ImageIcon(with the byte array)
       // and can create a label with that image
     }


I am really finding it hard to implement this.Waitin for your reply.
// can't check the code right now, so you might have some compilation errors.
// need to import java.io.*;
// need to import javax.swing.*;

InputStream in = part.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
// copy from inputStream to ByteArrayOutputStream
while ((len = in.read(bytes)) > 0)
              out.write(bytes, 0, len);

bytes = out.toByteArray();
Jlabel label = new Jlabel(new ImageIcon(bytes));
// add the labe to your swing application anywere you want

Thanks Aozarov,
I handled the label this way:

            JLabel label = new JLabel(new ImageIcon(bytes));            
            JFrame frame = new JFrame();
            Container c = frame.getContentPane();
            c.add(label);        
            c.setSize(300, 300);          
            c.show();

But when i run the program from command prompt, i get this:

D:\>java ReceiveImage
0: Harmeek Jhutty <xxx@hotmail.com> test
Content-Type: text/plain; format=flowed

hello
_________________________________________________________________
Designer Mail isn't just fun to send, it's fun to receive. Use special
stationery, fonts and colors.
http://join.msn.com/?pgmarket=en-ca&page=byoa/prem&xAPID=1994&DI=1034&SU=http://
hotmail.com/enca&HL=Market_MSNIS_Taglines
  Start enjoying all the benefits of MSN« Premium right now and get the
first two months FREE*.
Attachment: lug.gif : image/gif; name="lug.gif"

D:/>

Can you please tell me why the JFrame is not coming up.I am sorry for this..but I would be obliged if you could help me reaching the end.Thanks.
Can you send your full program?
Here it goes my friend,

public class ReceiveImage extends JFrame
{
       public static void main (String args[]) throws Exception {
 
             String host = "pop.broadband.rogers.com";
             String username = "xxx@rogers.com";              
             String password = "my_password";  
             Properties props = new Properties();

         Session session = Session.getDefaultInstance(props, null);

         Store store = session.getStore("pop3");
         store.connect(host, username, password);
         Folder folder = store.getFolder("INBOX");
         folder.open(Folder.READ_ONLY);
       
         BufferedReader reader = new BufferedReader (
         new InputStreamReader(System.in));

          // Get directory                
         Message message[] = folder.getMessages();
             for (int i=0, n=message.length; i<n; i++) {
               System.out.println(i + ": " + message[i].getFrom()[0]
                 + "\t" + message[i].getSubject());



         System.out.println("Do you want to read message? [YES toto read/QUIT to end]");
             String line = reader.readLine();
             if ("YES".equals(line)) {
                   Object content = message[i].getContent();
                   if (content instanceof Multipart) {
                                                handleMultipart((Multipart)content);
                                                } else {
                                                handlePart(message[i]);
                                }             

             //message[i].writeTo(System.out);
              } else if ("QUIT".equals(line)) {
                break;
              }
      }



folder.close(false);
store.close();
}

public static void handleMultipart(Multipart multipart) throws MessagingException,IOException
{
              for (int i=0, n=multipart.getCount(); i<n; i++) {
                  handlePart(multipart.getBodyPart(i));
}
}

public static void handlePart(Part part) throws MessagingException,IOException
{
      
                 String disposition = part.getDisposition();
            String contentType = part.getContentType();
           
            if (disposition == null) { // When just body
           
            MimeBodyPart mbp = (MimeBodyPart)part;
            if (mbp.isMimeType("text/plain")) {
            part.writeTo(System.out);
            } else { // Don't think this will happen
            if (mbp.isMimeType("image/gif")) {
              InputStream in = part.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            // copy from inputStream to ByteArrayOutputStream
            while ((len = in.read(bytes)) > 0)
              out.write(bytes, 0, len);

            bytes = out.toByteArray();
            JLabel label = new JLabel(new ImageIcon(bytes));            
            JFrame frame = new JFrame();
            Container c = frame.getContentPane();
            c.add(label);        
            c.setSize(300, 300);          
            c.show();

            }
        }
    }
            else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
            saveFile(part.getFileName(), part.getInputStream());
            } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
              System.out.println("Inline: " +
            part.getFileName() +
            " : " + contentType);
            saveFile(part.getFileName(), part.getInputStream());
            } else { // Should never happen
               
            System.out.println("Other: " + disposition);
}
}

public static void saveFile(String filename,InputStream input) {
            try{
            if (filename != null) {
            filename = "temporary.txt";
            }
            // Do no overwrite existing file
            File file = new File(filename);
            for (int i=0; file.exists(); i++) {
            file = new File(filename+i);
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            
            BufferedInputStream bis = new BufferedInputStream(input);
            int aByte;
            while ((aByte = bis.read()) != -1) {
                       bos.write(aByte);
            }
            bos.flush();
            bos.close();
            bis.close();
            }
catch(IOException exp){
//
}

}

}
I can't access pop3 here :-(
But from your output it seems that image is not embeded but rather is there as atachement (Attachment: lug.gif : image/gif; name="lug.gif")
So, to show it replace:

if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
            saveFile(part.getFileName(), part.getInputStream());
            }

with
if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
            showImage(part.getInputStream());
            }

// Adding a function to showImage (which is similar to the logic I gave you above) like:
public void showImage(InputStream input)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            // copy from inputStream to ByteArrayOutputStream
            while ((len = in.read(bytes)) > 0)
              out.write(bytes, 0, len);

            bytes = out.toByteArray();
            JLabel label = new JLabel(new ImageIcon(bytes));            
            JFrame frame = new JFrame();
            Container c = frame.getContentPane();
            c.add(label);        
            c.setSize(300, 300);          
            c.show();
}
Thanks Aozarov,
O.K i am sorry i was attaching it instead of embedding the image.But now,i tried doing both but i get this result:

For Embedded Image:
D:\>java ReceiveImage
0: xyz@rediffmail.com    Hello JavaMail
Do you want to read message? [YES to read/QUIT to end]
YES
D:\>

For attached Image:
D:\>java ReceiveImage
0: xyz@rediffmail.com    Hello JavaMail
Do you want to read message? [YES to read/QUIT to end]
YES
D:\>
Attachment: lug.gif : image/gif


Can you tell me...why the JFrame doesn't pop ups to show me the image,whereas i can see it in outlook express.See,if you can help.
Lets do that step by step.

Your logic just after:
System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
there is saveFile(part.getFileName(),
I can see this output "Attachment: lug.gif : image/gif"
Which means that the code is suppose to save a file "lug.gif".
do you see this file created? Can you open the file (with explorer or paintpbursh) to see if the file was saved ok?

If so, then instead of calling saveFile call to the function showImage which I gave you above (you will need to catch Exception the same
way you did for saveFile)

Did you do that? If not then put inside the add printStackTrace to the exception and send back the trace.
e.g. catch(Exception ex) { ex.printStackTrace; }
Thanks is getting too short a word now.....ok,we should go step by step.
Firstly,i replaced the savefile line with call to showImage() function,like this:


public static void handlePart(Part part) throws MessagingException,IOException
{
      
            String disposition = part.getDisposition();
            String contentType = part.getContentType();
           
            if (disposition == null) { // When just body
           
            MimeBodyPart mbp = (MimeBodyPart)part;
            if (mbp.isMimeType("text/plain")) {
            part.writeTo(System.out);
            } else { // Don't think this will happen
            if (mbp.isMimeType("image/gif")) {             
            try{
            showImage(part.getInputStream());
            }
            catch(IOException exp){
            exp.printStackTrace();
            }          
             

            }
        }
    }
            else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
           
            try{
            showImage(part.getInputStream());
            }
            catch(IOException exp){
            exp.printStackTrace();
            }          
         
            } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
              System.out.println("Inline: " +part.getFileName()+ " : " + contentType);
            try{
            showImage(part.getInputStream());
            }
            catch(IOException exp){
            exp.printStackTrace();
            }
           
            } else { // Should never happen
               
            System.out.println("Other: " + disposition);
}
}


But,I get the same result.And there's no problem with the image,because i get the same result with other images too i.e

D:\>java ReceiveImage
0: harmeek singh jhutty <mail4micky@rediffmail.com>     hi
Do you want to read message? [YES to read/QUIT to end]
YES
Attachment: lug.gif : image/gif

D:\>


Now,Tell me where I am goin wrong.
4 questions:

1. When the code had the saveFile logic (before this change) did it save the file as expected?
2. If the file was saved, was it saved correctly (could you for example look at it using explorer or pbrush applications) ?
3. I assume you don't see any stack trace or exceptions ?
4. can you put some printouts in the showImage like this (and provide it with your reponse):

public void showImage(InputStream input)
{
           ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
             System.out.println("before copying to ByteArrayOutputStream");
            // copy from inputStream to ByteArrayOutputStream
            while ((len = in.read(bytes)) > 0)
              out.write(bytes, 0, len);

            bytes = out.toByteArray();
            System.out.println("Getting bytes from outputStream -> " + bytes.length);
            JLabel label = new JLabel(new ImageIcon(bytes));            
            JFrame frame = new JFrame();
            Container c = frame.getContentPane();
            c.add(label);        
            c.setSize(300, 300);          
            System.out.println("Before frame show...");
            c.show();
}
Thanks Aozarov,
Here's the feedback:
First,When I try to save the file,its properly saved.....and when i open it up in the explorer it displays me the penguin(lug) image..so that means it works perfectly.
Second,I dont see any exceptions and here's the output with print outs inserted in the ShowImage method:

For inline image:

D:\>java ReceiveImage
0: xyz@rediffmail.com    Hello JavaMail
Do you want to read message? [YES to read/QUIT to end]
YES
before copying to ByteArrayOutputStream
Getting bytes from outputStream -> 8265

D:\>

For attached image:
D:\>java ReceiveImage
0: micky  <xyz@rediffmail.com>       hi
Do you want to read message? [YES to read/QUIT to end]
YES
Attachment: lug.gif : image/gif
before copying to ByteArrayOutputStream
Getting bytes from outputStream -> 8265

D:\>

what to do next man....sorry for the trouble....but i really wished i could make it work with your able guidance.Thanks.
>> roperly saved.....and when i open it up in the explorer it displays me the penguin(lug) image
That is great, which means you can generate the image bytes correctly
Regarding the output:

1. Getting bytes from outputStream -> 8265 (is the size of the file really 8K,)?
2. I don't see: System.out.println("Before frame show..."); message
3. Do you see any Swing frame? (even without the image)
4. I assume that you are running on environment that can show GUI (like windows, Xwindows,...)
5. can you add more printouts (after each line in showImage [copy paste the java line and display it as a string])

It seems that you are on the right track and we just need to make that frame popup.
Thanks Aozarov,
Here are the results:

>>1. Getting bytes from outputStream -> 8265 (is the size of the file really 8K,)?
Ya,thats the exact image size..i see from image properties.
>>2. I don't see: System.out.println("Before frame show..."); message
>>3. Do you see any Swing frame? (even without the image)
no..nothing at all
>>4. I assume that you are running on environment that can show GUI (like windows, >>Xwindows,...)
Ya,because all my other apllet programs are working fine.Im on WInXP.
>>5. can you add more printouts (after each line in showImage [copy paste the java line >>and display it as a string])
Here's the result,after adding a printout after each line:

D:\>java ReceiveImage
0: Harmeek Jhutty <xxx@hotmail.com> hi
Do you want to read message? [YES to read/QUIT to end]
YES
Content-Type: text/plain; format=flowed



_________________________________________________________________
Powerful Parental Controls Let your child discover the best the Internet has
to offer.
http://join.msn.com/?pgmarket=en-ca&page=byoa/prem&xAPID=1994&DI=1034&SU=http://
hotmail.com/enca&HL=Market_MSNIS_Taglines
  Start enjoying all the benefits of MSN« Premium right now and get the
first two months FREE*.
Attachment: lug.gif : image/gif; name="lug.gif"
before copying to ByteArrayOutputStream
Getting bytes from outputStream -> 8265
before JFrame
before coontainer line
before add
before setsize
before show method
after show method

D:\>


See,if this helps..or we cud end it the way it is...lolz
ASKER CERTIFIED SOLUTION
Avatar of aozarov
aozarov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thts it.....man
You rock aozarov...you seriously rock.I cant explain you the happiness i got when i saw the JFrame pop up with the image in it.I dont know how to pay you back..these points are nothing compared to all the help,guidance and time you have given for this problem man.I really thanks you from the core of my heart.Thanks.
:-)
You might want to add this line:
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
before
frame.show();

see http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation(int) for more info

I am always happy to assist :-)