Example usage for javax.mail Folder create

List of usage examples for javax.mail Folder create

Introduction

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

Prototype

public abstract boolean create(int type) throws MessagingException;

Source Link

Document

Create this folder on the Store.

Usage

From source file:org.apache.hupa.server.handler.CreateFolderHandler.java

@Override
protected GenericResult executeInternal(CreateFolder action, ExecutionContext context) throws ActionException {
    User user = getUser();/*from   w  w w .  j  a va  2  s  . c om*/
    IMAPFolder folder = action.getFolder();

    try {
        IMAPStore store = cache.get(user);
        Folder f = store.getFolder(folder.getFullName());
        if (f.create(Folder.HOLDS_MESSAGES)) {
            logger.info("Successfully create folder " + folder + " for user " + user);
            return new GenericResult();
        } else {
            logger.info("Unable to create folder " + folder + " for user " + user);
            throw new ActionException("Unable to create folder " + folder + " for user " + user);

        }
    } catch (Exception e) {
        logger.error("Error while creating folder " + folder + " for user " + user, e);
        throw new ActionException("Error while creating folder " + folder + " for user " + user, e);
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * @param folder//from  w  ww  .  j ava  2  s.c o m
 * @param message
 * @throws MessagingException
 */
public void write(String folder, Message message) throws MessagingException {
    // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder);

    final Store store = getJavamailStore(true);
    store.connect();
    final Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    if (!mailFolder.exists()) {
        mailFolder.create(Folder.HOLDS_MESSAGES);
    }
    mailFolder.open(Folder.READ_WRITE);
    // If message is already archived, do nothing
    final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]);
    if (existingMessage == null) {
        // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only
        // So we clone the message before storing it
        final MimeMessage cloned = cloneEmail(message);
        mailFolder.appendMessages(new Message[] { cloned });
    }

    mailFolder.close(true);
    store.close();
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from   ww w  .j a va2s  . c o  m
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    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("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

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

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                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, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

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

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;/*w ww . j  a  va  2s  .c  o  m*/
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    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("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

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

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                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, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

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

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Opens the named folder in READ/WRITE mode
 *
 * @throws MessagingException if there is a comms error or if the folder could not
 * be found or we failed to create it/* w  w  w  . jav a  2s .  c  o  m*/
 */
public Folder openFolder(String fldr, boolean create) throws MessagingException {
    if (store == null || !store.isConnected())
        connect();

    Folder f = store.getFolder(fldr);
    log.debug("Folder [" + fldr + "] exists? " + f.exists());

    // Note that a Folder object is returned even if the named folder does not
    // physically exist on the Store so we have to test for it explicitly.
    if (!f.exists()) {
        // we've not been asked to create the folder so this is an error
        if (!create)
            throw new MessagingException("Error opening folder [" + fldr + "]: Folder not found");

        // try to create the folder
        if (!f.create(Folder.HOLDS_MESSAGES))
            throw new MessagingException("Failed to create folder [" + fldr + "]");

        log.info("Created folder [" + fldr + "]");
    }

    f.open(Folder.READ_WRITE);
    log.debug("Folder [" + fldr + "] opened");

    return f;
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

public IMailFolder createFolder(String parentFolderId, String folderName) throws MailFolderException {

    try {/*from  www  .ja v a  2s .  c  o  m*/

        String newFolderName = null;
        if (!StringUtils.isEmpty(parentFolderId)) {
            newFolderName = parentFolderId + getFolderSeparator() + folderName;
        } else {
            newFolderName = folderName;
        }

        Folder newFolder = this.store.getFolder(newFolderName);
        if (!newFolder.exists()) {
            logger.debug("Createing folder... " + newFolderName);
            newFolder.create(Folder.HOLDS_MESSAGES);
        } else {
            throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null);
        }
        loadMailFolder();

        return createMailFolder(newFolder);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_CREATE, ex);
    }
}

From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java

public IMailFolder createFolder(String parentFolderId, String folderName) throws MailFolderException {

    try {//from   w  w  w  .  j a v  a  2s.  c o m

        String newFolderName = null;
        if (!StringUtils.isEmpty(parentFolderId)) {
            newFolderName = parentFolderId + getFolderSeparator() + folderName;
        } else {
            newFolderName = folderName;
        }

        Folder newFolder = this.store.getFolder(newFolderName);
        if (!newFolder.exists()) {
            log.debug("Creating folder... " + newFolderName);
            boolean success = newFolder.create(Folder.HOLDS_MESSAGES);
            if (!success) {
                throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_CREATE, null);
            }
            newFolder.setSubscribed(true);
        } else {
            throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null);
        }
        loadMailFolder();

        return createMailFolder(newFolder);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_CREATE, ex);
    }
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);/*from  w  w w.  ja v a2 s .  c  o  m*/
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}

From source file:com.sonicle.webtop.mail.MailAccount.java

public Folder checkCreateFolder(String foldername) throws MessagingException {
    Folder folder = store.getFolder(foldername);
    if (!folder.exists()) {
        folder.create(Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS);
    }/*from ww  w.j  a  v  a 2  s .  com*/
    return folder;
}

From source file:com.sonicle.webtop.mail.MailAccount.java

public String renameFolder(String orig, String newname) throws MessagingException {
    FolderCache fc = getFolderCache(orig);
    FolderCache fcparent = fc.getParent();
    Folder oldfolder = fc.getFolder();//  w w  w.java 2s.  com
    destroyFolderCache(fc);
    Folder newfolder = fcparent.getFolder().getFolder(newname);
    boolean done = oldfolder.renameTo(newfolder);
    if (!done) {
        throw new MessagingException("Rename failed");
    }

    //trick for Dovecot on NethServer: under shared folders, create and destroy a fake folder
    //or rename will not work correctly
    if (isUnderSharedFolder(newfolder.getFullName())) {
        Map<String, String> map = ((IMAPStore) store).id(null);
        if (map != null && map.containsKey("name") && map.get("name").equalsIgnoreCase("dovecot")) {
            String trickName = "_________" + System.currentTimeMillis();
            Folder trickFolder = fcparent.getFolder().getFolder(trickName);
            try {
                trickFolder.create(Folder.READ_ONLY);
                trickFolder.delete(true);
            } catch (MessagingException exc) {

            }
        }
    }

    addFoldersCache(fcparent, newfolder);
    return newfolder.getFullName();
}