Example usage for javax.mail Folder getMessage

List of usage examples for javax.mail Folder getMessage

Introduction

In this page you can find the example usage for javax.mail Folder getMessage.

Prototype

public abstract Message getMessage(int msgnum) throws MessagingException;

Source Link

Document

Get the Message object corresponding to the given message number.

Usage

From source file:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;/*from  w ww.j  a va 2  s. c o m*/
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            msgnum = Integer.parseInt(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (msgnum == -1) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message number: " + msgnum);
            Message m = null;

            try {
                m = folder.getMessage(msgnum);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;// w w w . ja v  a2 s.  c  o  m
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from   ww  w .  j  ava 2  s. c  om
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;/*from www.j  av a2 s .  c  o m*/
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Mark a given {@link GmailMessage} as read.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to mark {@link GmailMessage} as read
 *//*from w  w w  . j  a  va2 s .  co m*/
public void markAsRead(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (!message.isSet(Flags.Flag.SEEN)) {
            message.setFlag(Flags.Flag.SEEN, true);
        }
    } catch (Exception e) {
        throw new GmailException("ImapGmailClient failed marking" + " GmailMessage as read : " + messageNumber,
                e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Mark a given {@link GmailMessage} as unread.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to mark {@link GmailMessage} as unread
 *///from   w ww.j  a  v  a 2s  .c  o  m
public void markAsUnread(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (message.isSet(Flags.Flag.SEEN)) {
            message.setFlag(Flags.Flag.SEEN, false);
        }
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed marking" + " GmailMessage as unread : " + messageNumber, e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Flag a given {@link GmailMessage} as Starred.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to flag {@link GmailMessage} as starred
 *//*from   w  ww .ja  v  a 2 s .com*/
public void addStar(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (!message.isSet(Flags.Flag.FLAGGED)) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed flagging" + " GmailMessage as starred : " + messageNumber, e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Removes Star Flag of a given Starred {@link GmailMessage}.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to remove star flag from {@link GmailMessage}
 *//*from  w w  w. j a  va  2  s  .  c om*/
public void removeStar(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(ImapGmailLabel.STARRED.getName(), store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (message.isSet(Flags.Flag.FLAGGED)) {
            message.setFlag(Flags.Flag.FLAGGED, false);
        }
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed removing" + " GmailMessage star flag : " + messageNumber, e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Move {@link GmailMessage} to a given destination folder.
 *
 * @param destFolder the destination {@link Folder} name.See {@see ImapGmailLabel}
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if it fails to move {@link GmailMessage} to the
 * destination folder/*from  ww w .  j  a  v a 2s.  c  o m*/
 */
public void moveTo(ImapGmailLabel destFolder, int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid GmailMessage number");
    }

    Folder fromFolder = null;
    Folder toFolder = null;

    try {
        final Store store = openGmailStore();
        fromFolder = getFolder(this.srcFolder, store);
        fromFolder.open(Folder.READ_WRITE);
        Message message = fromFolder.getMessage(messageNumber);

        if (message != null) {
            toFolder = getFolder(destFolder.getName(), store);

            if (fromFolder.getURLName().equals(toFolder.getURLName())) {
                throw new GmailException("ImapGmailClient cannot move " + "GmailMessage within same folder "
                        + "(from " + fromFolder.getFullName() + " to " + toFolder.getFullName() + ")");
            }
            // copy from source folder to destination folder
            fromFolder.copyMessages(new Message[] { message }, toFolder);
            // move the copied message to trash folder
            moveToTrash(new GmailMessage[] { new JavaMailGmailMessage(message) });
        }
    } catch (GmailException ge) {
        throw ge;
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed moving" + " GmailMessage from " + fromFolder.getFullName(), e);
    } finally {
        closeFolder(fromFolder);
    }
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * //from w w w  .  j a v a2  s  .  c  o  m
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}