从退回邮件中读取附件名称

时间:2015-07-06 08:35:22

标签: java email javamail

我正试图从退回的邮件中读取附件的名称。这是我能够获得它的一种方式,但我想知道是否有更好的方法来实现它。这非常耗时。

BufferedReader reader = new BufferedReader(new StringReader(message.getContent().toString()));
while ((str = reader.readLine()) != null)  {
    index = str.indexOf("filename");
    if(index >-1){
        filename = str.substring(index+9); 
        if (filename.length() > 0) System.out.println("Attachment  : " + filename);
    }
}

以下是完整的代码。

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.Properties;
import java.util.Scanner;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

public class CheckingMail {

    public static void check(String host, String storeType, String user, String password) 
    {
        try {
            Properties properties = new Properties();

            properties.put("mail.imap.host", host);
            properties.put("mail.imap.port", "993");
            properties.put("mail.imap.starttls.enable", "true");

            Session emailSession = Session.getDefaultInstance(properties);

            Store store = emailSession.getStore("imaps");

            store.connect(host, user, password);

            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_WRITE);

            System.out.println("emailFolder.hasNewMessages()---" + emailFolder.hasNewMessages());
            System.out.println("emailFolder.getNewMessageCount---" + emailFolder.getNewMessageCount());
            System.out.println("emailFolder.getUnreadMessageCount---" + emailFolder.getUnreadMessageCount());


            Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.RECENT), false)); 
            System.out.println("messages.length---" + messages.length);
            int bcnt = 0;
            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                if(message.getFrom()[0].toString().contains("MAILER-DAEMON")){
                    bcnt++;
                }
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);

                long start = System.currentTimeMillis();
                int index = -1;
                BufferedReader reader = new BufferedReader(new StringReader(message.getContent().toString()));
                String str = "" , filename = "";

                while ((str = reader.readLine()) != null)  {
                    index = str.indexOf("filename");
                    if(index >-1){
                        filename = str.substring(index+9); 
                        if (filename.length() > 0) System.out.println("Attachment  : " + filename);
                    }
                }
                System.out.printf("Time : %d%n", System.currentTimeMillis() - start);

                for(int j=0;j<message.getAllRecipients().length; j++){
                    System.out.println("Recipients "+j+" : " + message.getAllRecipients()[j]);
                }
                System.out.println("Date: " + message.getSentDate());
            }
            System.out.println("Bounce count : " + bcnt);
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "imap.mail.yahoo.com";
        String mailStoreType = "imap";
        String username = "yourmail@yahoo.com";
        String password = "*****";

        check(host, mailStoreType, username, password);

    }

}

示例邮件

Sorry, we were unable to deliver your message to the following address.

<bounce@yahoo.fhdf>:
No MX or A records for yahoo.fhdf

--- Below this line is a copy of the message.

Received: from [ip] with NNFMP; 02 Jul 2015 07:26:24 -0000
Received: from [ip] with NNFMP; 02 Jul 2015 07:23:24 -0000
Received: from [ip] with NNFMP; 02 Jul 2015 07:23:21 -0000
Received: from [ip] with NNFMP; 02 Jul 2015 07:23:21 -0000
Received: from [] with NNFMP; 02 Jul 2015 07:23:21 -0000
X-Yahoo-Newman-Property: ymail-4
X-Yahoo-Newman-Id: 413220.37634.bm@omp1027.mail.ir2.yahoo.com
X-YMail-OSG: ByrxKJsVM1ngLTK9ms.eLuFTCEl6w0XU0HtbGqwE70HR4CtF8BU_giAhODvLvMc
NiITUbpoTi2nhfKQ0WnxsPY4KMJyCRONlErkMhBA8a_bi7HLGeUqj53lPEgJ9oZtyTxykF4OVqw8
e3Y0LO_rgeE49pQzvjFDNmE7L3kAePyzTbWfPv7Vper3tC8kWTTU21W5POlCB7LQ38FJoMsGOtSq
qRjYLEILpy6xk34mPTwiSXkIb8iU.--
Received: by 217.12.9.9; Thu, 02 Jul 2015 07:23:21 +0000 
Date: Thu, 2 Jul 2015 07:23:20 +0000 (UTC)
From: test <fromuserid@yahoo.com>
Reply-To: test <fromuserid@yahoo.com>
To: "bounce@yahoo.fhdf" <bounce@yahoo.fhdf>
Message-ID: <443022398.1267465.1435821801286.JavaMail.yahoo@mail.yahoo.com>
Subject: 
MIME-Version: 1.0
Content-Type: multipart/mixed; 
    boundary="----=_Part_1267464_969780179.1435821801286"
Content-Length: 293584

------=_Part_1267464_969780179.1435821801286
Content-Type: multipart/alternative; 
    boundary="----=_Part_1267463_786603392.1435821801283"

------=_Part_1267463_786603392.1435821801283
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit



------=_Part_1267463_786603392.1435821801283
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit

<html><body><div style="color:#000; background-color:#fff; font-family:HelveticaNeue, Helvetica Neue, Helvetica, Arial, Lucida Grande, Sans-Serif;font-size:16px"><div id="yui_3_16_0_1_1435820944162_7576"><br></div></div></body></html>
------=_Part_1267463_786603392.1435821801283--

------=_Part_1267464_969780179.1435821801286
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=img-211134632-0001.pdf
Content-ID: <c95faa3b-7ec0-2555-6b65-cdab3f05aabb@yahoo.com>

JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PAovQ3JlYXRvciAoWGVyb3ggV29ya0NlbnRyZSA1MjMw

1 个答案:

答案 0 :(得分:1)

正如JavaMail FAQ中所述,这些退回邮件的标准,但并非所有服务器都实施该标准。你找到了一台这样的服务器。常见问题解答有其他可能有帮助的指针,但你几乎坚持使用启发式方法。如果您经常使用不支持该标准的特定邮件服务器,则可以通过识别来自此类服务器的退回邮件,使您的启发式方法更智能,更可靠。

例如,在上面的示例退回邮件中,似乎包含了邮件的整个原始MIME内容。您可以只提取该部分并使用MimeMessage constructor来解析它,并更轻松地提取文件名。