IMAPMail.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.examples.mail;

  18. import java.io.IOException;
  19. import java.net.URI;

  20. import org.apache.commons.net.PrintCommandListener;
  21. import org.apache.commons.net.imap.IMAPClient;

  22. /**
  23.  * This is an example program demonstrating how to use the IMAP[S]Client class. This program connects to a IMAP[S] server, lists its capabilities and shows the
  24.  * status of the Inbox.
  25.  * <p>
  26.  * Usage: IMAPMail imap[s]://user:password@server/
  27.  * <p>
  28.  * For example<br>
  29.  * IMAPMail imaps://user:password@imap.mail.yahoo.com/<br>
  30.  * or<br>
  31.  * IMAPMail imaps://user:password@imap.googlemail.com/
  32.  */
  33. public final class IMAPMail {

  34.     public static void main(final String[] args) throws IOException {
  35.         if (args.length != 1) {
  36.             System.err.println("Usage: IMAPMail imap[s]://user:password@server/");
  37.             System.err.println("Connects to server; lists capabilities and shows Inbox status");
  38.             System.exit(1);
  39.         }

  40.         final URI uri = URI.create(args[0]);

  41.         // Connect and login
  42.         final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null);

  43.         // suppress login details
  44.         imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));

  45.         try {
  46.             imap.setSoTimeout(6000);

  47.             imap.capability();

  48.             imap.select("inbox");

  49.             imap.examine("inbox");

  50.             imap.status("inbox", new String[] { "MESSAGES" });

  51.             imap.list("", "*"); // Show the folders

  52.         } catch (final IOException e) {
  53.             System.out.println(imap.getReplyString());
  54.             e.printStackTrace();
  55.             System.exit(10);
  56.         } finally {
  57.             imap.logout();
  58.             imap.disconnect();
  59.         }
  60.     }
  61. }