【问题标题】:Java Mail API: Convert Message to String?Java Mail API:将消息转换为字符串?
【发布时间】:2015-07-14 05:20:50
【问题描述】:

我正在使用以下代码从我的 Gmail 帐户中成功检索邮件。

// Import Statements 

    public class ConfirmEmail {

    WebDriver driver;
    Folder inbox;

    String gmailID = "xxxxxxxxxxx@gmail.com";
    String gmailPass = "xxxxxxxx";
    String storeMessage;

    public ConfirmEmail()
    {

    }

    public void MailReader() {
        System.out.println("Inside MailReader()...");
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        /* Set the mail properties */

        Properties props = System.getProperties();
        // Set manual Properties
        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
        props.setProperty("mail.pop3.port", "995");
        props.setProperty("mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.host", "pop.gmail.com");

        try

        {

            /* Create the session and get the store for read the mail. */

            Session session = Session.getDefaultInstance(
                    System.getProperties(), null);

            Store store = session.getStore("pop3");

            store.connect("pop.gmail.com", 995, gmailID,
                    gmailPass);

            /* Mention the folder name which you want to read. */

            // inbox = store.getDefaultFolder();
            // inbox = inbox.getFolder("INBOX");
            inbox = store.getFolder("INBOX");

            /* Open the inbox using store. */

            inbox.open(Folder.READ_ONLY);

            /* Get the messages which is unread in the Inbox */

            Message messages[] = inbox.search(new FlagTerm(new Flags(
                    Flags.Flag.SEEN), false));
            System.out.println("No. of Unread Messages : " + messages.length);

            /* Use a suitable FetchProfile */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);

            fp.add(FetchProfile.Item.CONTENT_INFO);

            inbox.fetch(messages, fp);

            try

            {

                printAllMessages(messages);

                inbox.close(true);
                store.close();

            }

            catch (Exception ex)

            {
                System.out.println("Exception arise at the time of read mail");

                ex.printStackTrace();

            }

        }

        catch (MessagingException e)
        {
            System.out.println("Exception while connecting to server: "
                    + e.getLocalizedMessage());
            e.printStackTrace();
            System.exit(2);
        }

    }

    public void printAllMessages(Message[] msgs) throws Exception
    {
        for (int i = 0; i < msgs.length; i++)
        {

            System.out.println("MESSAGE #" + (i + 1) + ":");

            printEnvelope(msgs[i]);
        }

    }

    public void printEnvelope(Message message) throws Exception

    {

        Address[] a;

        // FROM

        if ((a = message.getFrom()) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();

        Date receivedDate = message.getReceivedDate();
        Date sentDate = message.getSentDate(); // receivedDate is returning
                                                // null. So used getSentDate()

        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        if (receivedDate != null) {
            System.out.println("Received Date : " + receivedDate.toString());
        }
        System.out.println("Sent Date : " + sentDate.toString());
        System.out.println("Content : " + content);

        getContent(message);

    }





    public void getContent(Message msg)

    {
        try {
            String contentType = msg.getContentType();
            System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();

            for (int i = 0; i < count; i++) {
                dumpPart(mp.getBodyPart(i));
            }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1) {
            System.out.write(c);


        }
    }



}

使用此代码,我可以成功地将消息打印到控制台。 100% 的时间完美无瑕。

但是,我需要将“bodyPart”(即实际消息或消息正文)存储在字符串中,以便可以使用正则表达式搜索字符串。我需要提取以 http 开头的链接。

如何将消息转换为字符串?

谢谢

【问题讨论】:

    标签: java regex string jakarta-mail


    【解决方案1】:

    我不太确定你在问什么(因为你说你已经打印出了你的消息......所以当你打印它们时,为什么不能将它们存储在字符串中?)

    如果您真的只想将 bodyPart 存储在 String 变量中:

    Multipart mp = (Multipart) msg.getContent();
    BodyPart bp = mp.getBodyPart(0);
    String content = bp.getContent().toString();
    

    【讨论】:

    • 它工作并给了我完整的正文内容作为一个字符串。但在我的邮件中有 URL。我想要那个 URL 原样。但上面的代码给了我href。我怎样才能只获取 URL?
    猜你喜欢
    • 2011-12-09
    • 2020-12-13
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2013-01-29
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多