Results 1 to 7 of 7
  1. #1
    asai is offline Senior Member
    Join Date
    Feb 2012
    Location
    Norway
    Posts
    135
    Rep Power
    0

    Default pop3 java mail download

    Hi
    I am working on a little project for automatic receiving e-mails.
    I have managed to download mail from a pop3 mailaccount.
    My problem is that I cant figure out how to receive mail with both text in message field and attachment in the same mail.
    I am able to receive mail with just message or saving attachment. I would like to do both in the same mail.

    Heres my code:
    Java Code:
    public void downloadEmailAttachments(String host, String port, String userName, String password) {
            Properties properties = new Properties();
            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", port);
     
            // SSL setting
            properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.pop3.socketFactory.fallback", "false");
            properties.setProperty("mail.pop3.socketFactory.port",
            String.valueOf(port));
     
            Session session = Session.getDefaultInstance(properties);
     
            try {
                Store store = session.getStore("pop3");
                store.connect(userName, password);
     
                Folder folderInbox = store.getFolder("INBOX");
                folderInbox.open(Folder.READ_ONLY);
     
                Message[] arrayMessages = folderInbox.getMessages();
     
                for (int i = 0; i < arrayMessages.length; i++) {
                    Message message = arrayMessages[i];
                    Address[] fromAddress = message.getFrom();
                    String from = fromAddress[0].toString();
                    String subject = message.getSubject();
                    String sentDate = message.getSentDate().toString();
     
                    String contentType = message.getContentType();
                    String messageContent = "";
     
                    String attachFiles = "";
     
                    if (contentType.contains("multipart")) {
                        // content may contain attachments
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                // this part is attachment
                                String fileName = part.getFileName();
                                attachFiles += fileName + ", ";
                                part.saveFile(saveDirectory + File.separator + fileName);
                            } else {
                                // this part may be the message content
                                messageContent = part.getContent().toString();
                            }
                        }
     
                        if (attachFiles.length() > 1) {
                            attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    }
     
                    String strippedText = messageContent.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
                    // print out details of each message
                    System.out.println("Message #" + (i + 1) + ":");
                    System.out.println("\t From: " + from);
                    System.out.println("\t Subject: " + subject);
                    System.out.println("\t Sent Date: " + sentDate);
                    System.out.println("\t Message: " + strippedText);
                    System.out.println("\t Attachments: " + attachFiles);
                    
                    
                }
     
                // disconnect
                folderInbox.close(false);
                store.close();
            } catch (NoSuchProviderException ex) {
                System.out.println("No provider for pop3.");
                ex.printStackTrace();
            } catch (MessagingException ex) {
                System.out.println("Could not connect to the message store");
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    Any help would be appreciated. :)

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: pop3 java mail download

    That's a long method.

    Anyway, put some debugging code in there, especially around the iterating over the multiparts and log what is being encountered, like how many there are and what they are.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,170
    Rep Power
    12

    Default Re: pop3 java mail download

    I did this many years ago using Perl (before Java existed). But my background in protocol implementation helped. I simply used pattern
    matching to parse the message and also wrote a Base64 converter to decode the attachments. It was not a 100% implementation
    but it served my purpose.

    But my first recommendation would be to read the appropriate RFC for message formatting including MIME attachments
    so you have an idea of how all this works. It will then, imho, make more sense when applying the Java API to extract and convert
    the appropriate parts of the message.

    You may also want to write some utility methods to help make your code more readable.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    asai is offline Senior Member
    Join Date
    Feb 2012
    Location
    Norway
    Posts
    135
    Rep Power
    0

    Default Re: pop3 java mail download

    Her is what the message look like when I receive a e-mail with attachement:

    Java Code:
    Message: com.sun.mail.util.BASE64DecoderStream@752325ad

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,951
    Rep Power
    7

    Default Re: pop3 java mail download

    As soon as you see @453645 that's the toString of Object. You need to do something with that object. You can't just slap a toString() on it and hope that it works. Most likely you need to wrap this stream into a BufferedInputStream and read it.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  6. #6
    asai is offline Senior Member
    Join Date
    Feb 2012
    Location
    Norway
    Posts
    135
    Rep Power
    0

    Default Re: pop3 java mail download

    Ok, so I have played around a bit with the code...
    Have som success, but a little to much output.

    Java Code:
    if (contentType.startsWith("TEXT/PLAIN")|| contentType.startsWith("TEXT/HTML") || contentType.startsWith("com.sun.mail.util.BASE64DecoderStream")) {
                InputStream is = messagePart.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String thisLine = reader.readLine();
                    while (thisLine != null) {
                    System.out.println(thisLine);
                    thisLine = reader.readLine();
                }
    In the body of the mail I have "Hello world!"

    However this is what the output looks like:
    Java Code:
    ------=_NextPart_001_08C9_01D3CD78.5F76B0E0
    Content-Type: text/plain;
    	charset="us-ascii"
    Content-Transfer-Encoding: 7bit
    
    Hello world!
    
    
    ------=_NextPart_001_08C9_01D3CD78.5F76B0E0
    Content-Type: text/html;
    	charset="us-ascii"
    Content-Transfer-Encoding: quoted-printable
    
    <html xmlns:v=3D"urn:schemas-microsoft-com:vml" =
    xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
    xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
    xmlns:m=3D"http://schemas.microsoft.com/office/2004/12/omml" =
    xmlns=3D"http://www.w3.org/TR/REC-html40"><head><META =
    HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
    charset=3Dus-ascii"><meta name=3DGenerator content=3D"Microsoft Word 15 =
    (filtered medium)"><style><!--
    /* Font Definitions */
    @font-face
    	{font-family:"Cambria Math";
    	panose-1:2 4 5 3 5 4 6 3 2 4;}
    @font-face
    	{font-family:Calibri;
    	panose-1:2 15 5 2 2 2 4 3 2 4;}
    /* Style Definitions */
    p.MsoNormal, li.MsoNormal, div.MsoNormal
    	{margin:0cm;
    	margin-bottom:.0001pt;
    	font-size:11.0pt;
    	font-family:"Calibri",sans-serif;
    	mso-fareast-language:EN-US;}
    a:link, span.MsoHyperlink
    	{mso-style-priority:99;
    	color:#0563C1;
    	text-decoration:underline;}
    a:visited, span.MsoHyperlinkFollowed
    	{mso-style-priority:99;
    	color:#954F72;
    	text-decoration:underline;}
    span.EpostStil17
    	{mso-style-type:personal-compose;
    	font-family:"Calibri",sans-serif;
    	color:windowtext;}
    .MsoChpDefault
    	{mso-style-type:export-only;
    	font-family:"Calibri",sans-serif;
    	mso-fareast-language:EN-US;}
    @page WordSection1
    	{size:612.0pt 792.0pt;
    	margin:70.85pt 70.85pt 70.85pt 70.85pt;}
    div.WordSection1
    	{page:WordSection1;}
    --></style><!--[if gte mso 9]><xml>
    <o:shapedefaults v:ext=3D"edit" spidmax=3D"1026" />
    </xml><![endif]--><!--[if gte mso 9]><xml>
    <o:shapelayout v:ext=3D"edit">
    <o:idmap v:ext=3D"edit" data=3D"1" />
    </o:shapelayout></xml><![endif]--></head><body lang=3DNO-BOK =
    link=3D"#0563C1" vlink=3D"#954F72"><div class=3DWordSection1><p =
    class=3DMsoNormal>Hello world!<o:p></o:p></p></div></body></html>
    ------=_NextPart_001_08C9_01D3CD78.5F76B0E0--
    But I don't want all this. How can i filter the content I want?

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: pop3 java mail download

    Did you do what Jim suggested:
    read the appropriate RFC for message formatting including MIME attachments
    That explains the format of what you have printed.
    Looks like you need to write code to extract the part(s) of the message you are interested in.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 5
    Last Post: 03-21-2014, 01:03 PM
  2. Mail reading issue using pop3 in java mailing
    By aby in forum Advanced Java
    Replies: 6
    Last Post: 03-18-2014, 09:15 AM
  3. Replies: 1
    Last Post: 05-18-2011, 02:08 AM
  4. Send / Receive mail and download attachment
    By Thennarasu in forum Advanced Java
    Replies: 1
    Last Post: 05-29-2009, 11:59 PM
  5. Replies: 2
    Last Post: 05-05-2008, 06:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •