Example usage for javax.mail Folder exists

List of usage examples for javax.mail Folder exists

Introduction

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

Prototype

public abstract boolean exists() throws MessagingException;

Source Link

Document

Tests if this folder physically exists on the Store.

Usage

From source file:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command./*from   www  .  j a va 2s  .  co m*/
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    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("-a")) {
            file = 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("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-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] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        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);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

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

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        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);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

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

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

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

        /*
         * Save a copy of the message, 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) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder and read messages until it founds the magic subject,
 * then gets the attachment which contains the data and return the serialized object stored.
 *///  w ww  . j av  a 2s.  c  o  m
protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName,
        String magicType) throws MessagingException, IOException, ClassNotFoundException {
    Folder folder = iStore.getFolder(folderName);
    if (folder.exists()) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        Message message = null;
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (magicType.equals(msg.getSubject())) {
                message = msg;
                break;
            }
        }
        if (message != null) {
            Object con = message.getContent();
            if (con instanceof Multipart) {
                Multipart mp = (Multipart) con;
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart part = mp.getBodyPart(i);
                    if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) {
                        ObjectInputStream ois = new ObjectInputStream(part.getInputStream());
                        Object o = ois.readObject();
                        ois.close();
                        logger.info("Returning user preferences of type " + magicType + " from imap folder + "
                                + folderName + " for user " + user);
                        return o;
                    }
                }
            }
        }
    }
    return null;
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;// w  w w  .j a  v a  2 s .  c om
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*  www .  j a v a2 s .  c om*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:com.email.ReceiveEmail.java

/**
 * This account fetches emails from a specified account and marks the emails
 * as seen, only touches the email account does not delete or move any
 * information./*from  w w w.j  a  v  a  2s  .c  o m*/
 *
 * @param account SystemEmailModel
 */
public static void fetchEmail(SystemEmailModel account) {
    Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
    Properties properties = EmailProperties.setEmailInProperties(account);

    try {
        Session session = Session.getInstance(properties, auth);
        Store store = session.getStore();
        store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(),
                account.getPassword());
        Folder fetchFolder = store.getFolder(account.getIncomingFolder());
        if (account.getIncomingFolder().trim().equals("")) {
            fetchFolder = store.getFolder("INBOX");
        }

        if (fetchFolder.exists()) {
            fetchFolder.open(Folder.READ_WRITE);
            Message[] msgs = fetchFolder.getMessages();

            // USE THIS FOR UNSEEN MAIL TO SEEN MAIL
            //Flags seen = new Flags(Flags.Flag.SEEN);
            //FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            //Message[] msgs = fetchFolder.search(unseenFlagTerm);
            //fetchFolder.setFlags(msgs, seen, true);
            if (msgs.length > 0) {
                List<String> messageList = new ArrayList<>();

                for (Message msg : msgs) {
                    boolean notDuplicate = true;
                    String headerText = Arrays.toString(msg.getHeader("Message-ID"));

                    for (String header : messageList) {
                        if (header.equals(headerText)) {
                            notDuplicate = false;
                            break;
                        }
                    }

                    if (notDuplicate) {
                        //Add to header to stop duplicates
                        messageList.add(headerText);
                        attachmentCount = 1;
                        attachmentList = new ArrayList<>();

                        //Setup Email For dbo.Email
                        EmailMessageModel eml = new EmailMessageModel();
                        String emailTime = String.valueOf(new Date().getTime());
                        eml.setSection(account.getSection());
                        eml = saveEnvelope(msg, msg, eml);
                        eml.setId(EMail.InsertEmail(eml));

                        //After Email has been inserted Gather Attachments
                        saveAttachments(msg, msg, eml);

                        //Create Email Body
                        eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList);

                        //Insert Email Body As Attachment (so it shows up in attachment table during Docketing)
                        EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName());

                        //Flag email As ready to file so it is available in the docket tab of SERB3.0
                        eml.setReadyToFile(1);
                        EMail.setEmailReadyToFile(eml);
                    }

                    if (deleteEmailEnabled) {
                        //  Will Delete message from server
                        //  Un Comment line below to run
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
            }
            fetchFolder.close(true);
            store.close();
        }
    } catch (MessagingException ex) {
        if (ex != null) {
            System.out.println("Unable to connect to email Server for: " + account.getEmailAddress()
                    + "\nPlease ensure you are connected to the network and" + " try again.");
        }
        ExceptionHandler.Handle(ex);
    }
}

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

/**
 * @param folder//w  w  w  .  ja v a2  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: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  .j av 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:org.eurekastreams.server.service.email.ImapEmailIngester.java

/**
 * Ingests email from a mailbox.//from   www.ja  v  a 2 s.c  o m
 */
public void execute() {
    // get message store
    Store store;
    try {
        long startTime = System.nanoTime();
        store = storeFactory.getStore();
        log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime);
    } catch (MessagingException ex) {
        log.error("Error getting message store.", ex);
        return;
    }
    try {
        // get folders
        Folder inputFolder = store.getFolder(inputFolderName);
        if (!inputFolder.exists()) {
            log.error("Input folder {} does not exist.", inputFolderName);
            return;
        }
        Folder successFolder = null;
        if (StringUtils.isNotBlank(successFolderName)) {
            successFolder = store.getFolder(successFolderName);
            if (!successFolder.exists()) {
                log.error("Success folder {} does not exist.", successFolderName);
                return;
            }
        }
        Folder discardFolder = null;
        if (StringUtils.isNotBlank(discardFolderName)) {
            discardFolder = store.getFolder(discardFolderName);
            if (!discardFolder.exists()) {
                log.error("Discard folder {} does not exist.", discardFolderName);
                return;
            }
        }
        Folder errorFolder = null;
        if (StringUtils.isNotBlank(errorFolderName)) {
            errorFolder = store.getFolder(errorFolderName);
            if (!errorFolder.exists()) {
                log.error("Error folder {} does not exist.", errorFolderName);
                return;
            }
        }

        inputFolder.open(Folder.READ_WRITE);

        // fetch messages
        // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE)
        // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached
        // body structure and thought that the content itself was cached, but I'd think a bug like that would have
        // been found by many people and fixed long ago, so I'm assuming it's something else.)
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        Message[] msgs = inputFolder.getMessages();
        inputFolder.fetch(msgs, fp);

        log.debug("About to process {} messages", msgs.length);

        // process each message
        if (msgs.length > 0) {
            List<Message> successMessages = new ArrayList<Message>();
            List<Message> errorMessages = new ArrayList<Message>();
            List<Message> discardMessages = new ArrayList<Message>();
            List<Message> responseMessages = new ArrayList<Message>();
            for (int i = 0; i < msgs.length; i++) {
                Message message = msgs[i];
                try {
                    boolean processed = messageProcessor.execute(message, responseMessages);
                    (processed ? successMessages : discardMessages).add(message);
                } catch (Exception ex) {
                    log.error("Failed to process email message.", ex);
                    errorMessages.add(message);
                }
            }

            // send response messages
            for (Message responseMessage : responseMessages) {
                emailerFactory.sendMail(responseMessage);
            }

            // move and purge messages
            if (successFolder != null && !successMessages.isEmpty()) {
                inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]),
                        successFolder);
            }
            if (discardFolder != null && !discardMessages.isEmpty()) {
                inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]),
                        discardFolder);
            }
            if (errorFolder != null && !errorMessages.isEmpty()) {
                inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder);
            }
            for (int i = 0; i < msgs.length; i++) {
                msgs[i].setFlag(Flag.DELETED, true);
            }

            log.info("{} messages processed:  {} successful, {} discarded, {} failed.", new Object[] {
                    msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() });
        }

        // close folder
        inputFolder.close(true);
    } catch (MessagingException ex) {
        log.error("Error ingesting email.", ex);
    } catch (Exception ex) {
        log.error("Error ingesting email.", ex);
    } finally {
        // close store
        try {
            store.close();
        } catch (MessagingException ex) {
            log.error("Error closing message store.", ex);
        }
    }
}

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  v  a2  s.  co 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;/*from  w  w w .  j  a va2 s  .  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();
    }
}