Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从退回的邮件中读取附件名称_Java_Email_Jakarta Mail - Fatal编程技术网

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

Java 从退回的邮件中读取附件名称,java,email,jakarta-mail,Java,Email,Jakarta Mail,我正试图从被退回的邮件中读取附件的名称。这里有一个方法,我可以得到它,但我想知道是否有更好的方法来做它。这相当耗时 BufferedReader reader = new BufferedReader(new StringReader(message.getContent().toString())); while ((str = reader.readLine()) != null) { index = str.indexOf("filename"); if(index &g

我正试图从被退回的邮件中读取附件的名称。这里有一个方法,我可以得到它,但我想知道是否有更好的方法来做它。这相当耗时

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);

    }

}
导入java.io.BufferedReader;
导入java.io.StringReader;
导入java.util.Properties;
导入java.util.Scanner;
导入javax.mail.Flags;
导入javax.mail.Folder;
导入javax.mail.Message;
导入javax.mail.MessaginException;
导入javax.mail.Multipart;
导入javax.mail.NoSuchProviderException;
导入javax.mail.Session;
导入javax.mail.Store;
导入javax.mail.search.FlagTerm;
公共类检查邮件{
公共静态无效检查(字符串主机、字符串存储类型、字符串用户、字符串密码)
{
试一试{
属性=新属性();
properties.put(“mail.imap.host”,host);
properties.put(“mail.imap.port”、“993”);
properties.put(“mail.imap.starttls.enable”、“true”);
会话emailSession=Session.getDefaultInstance(属性);
Store Store=emailSession.getStore(“imaps”);
store.connect(主机、用户、密码);
文件夹emailFolder=store.getFolder(“收件箱”);
emailFolder.open(Folder.READ\u WRITE);
System.out.println(“emailFolder.hasNewMessages()-”+emailFolder.hasNewMessages());
System.out.println(“emailFolder.getNewMessageCount----”+emailFolder.getNewMessageCount());
System.out.println(“emailFolder.GetUnderMessageCount----”+emailFolder.GetUnderMessageCount());
Message[]messages=emailFolder.search(新标志(Flags.Flag.RECENT),false);
System.out.println(“messages.length----”+messages.length);
int bcnt=0;
for(int i=0,n=messages.length;i-1){
filename=str.substring(索引+9);
如果(filename.length()>0)System.out.println(“附件:“+filename”);
}
}
System.out.printf(“时间:%d%n”,System.currentTimeMillis()-start);
对于(int j=0;j如中所述,对于此类被反弹的邮件有一个标准,但并非所有服务器都实现了该标准。您已经找到了一个这样的服务器。常见问题解答中有其他可能有所帮助的指针,但您几乎被试探法所困扰。如果您经常使用不支持该标准的特定邮件服务器,您可以使您的通过识别来自此类服务器的跳转消息,启发式更智能、更可靠


例如,在上面的“反弹邮件”示例中,邮件的整个原始MIME内容似乎都包含在内。您可以只提取该部分,然后使用来解析它,并更轻松地提取文件名。

这样一个“反弹邮件”示例会很有帮助。@realpoint我添加了一个“反弹邮件”示例我认为主要问题是你的方法缺乏可靠性——邮件中可能包含“filename”一词与附件无关。如果所有反弹的邮件都与示例类似,我可能会删除嵌入副本的所有行,然后将其解析为邮件并进行处理。这样会更可靠,但不一定效率更高。但并非所有反弹看起来都一样,甚至不会给您邮件的完整副本。@realpoint By embedded复制您是指实际的邮件正文吗?您是指类似这样的内容吗
InputStream stream=newbytearrayinputstream(message.getContent().toString().getBytes(Charset.forName(“UTF-8”));MimeMessage msg=new mimessage(emailSession,stream)
是否有其他方法可以从被退回邮件中读取附件名称和其他详细信息。正如您所说,并非所有服务器都实现了退回邮件的标准,有些服务器甚至在正文中没有附件的名称。是的,有点像这样,但是在包含邮件的MIME内容之前,您必须在开始时去掉这些内容.还有其他方法吗?当然。这是软件。总有另一种方法。但正如我所说的,它们不是具有可预测结果的算法,而是有时有效有时失败的启发式算法。你必须决定你愿意容忍哪种失败,并为你遇到的情况创建启发式算法到处闲逛。
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