Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

In this page you can find the example usage for javax.mail Session getInstance.

Prototype

public static Session getInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    Properties props = new Properties();
    props.put("mail.host", "mail.cloud9.net");

    Session mailConnection = Session.getInstance(props, null);
    Message msg = new MimeMessage(mailConnection);

    Address a = new InternetAddress("a@a.com", "A a");
    Address b = new InternetAddress("fake@java2s.com");

    msg.setContent("Mail contect", "text/plain");
    msg.setFrom(a);/*  www.j a v  a2  s. c om*/
    msg.setRecipient(Message.RecipientType.TO, b);
    msg.setSubject("subject");

    Transport.send(msg);
}

From source file:monitor.java

public static void main(String argv[]) {
    if (argv.length != 5) {
        System.out.println("Usage: monitor <host> <user> <password> <mbox> <freq>");
        System.exit(1);/*from   w  w  w .  ja v a2 s  .c  o m*/
    }
    System.out.println("\nTesting monitor\n");

    try {
        Properties props = System.getProperties();

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

        // Get a Store object
        Store store = session.getStore("imap");

        // Connect
        store.connect(argv[0], argv[1], argv[2]);

        // Open a Folder
        Folder folder = store.getFolder(argv[3]);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        // Add messageCountListener to listen for new messages
        folder.addMessageCountListener(new MessageCountAdapter() {
            public void messagesAdded(MessageCountEvent ev) {
                Message[] msgs = ev.getMessages();
                System.out.println("Got " + msgs.length + " new messages");

                // Just dump out the new messages
                for (int i = 0; i < msgs.length; i++) {
                    try {
                        System.out.println("-----");
                        System.out.println("Message " + msgs[i].getMessageNumber() + ":");
                        msgs[i].writeTo(System.out);
                    } catch (IOException ioex) {
                        ioex.printStackTrace();
                    } catch (MessagingException mex) {
                        mex.printStackTrace();
                    }
                }
            }
        });

        // Check mail once in "freq" MILLIseconds
        int freq = Integer.parseInt(argv[4]);
        boolean supportsIdle = false;
        try {
            if (folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
                supportsIdle = true;
            }
        } catch (FolderClosedException fex) {
            throw fex;
        } catch (MessagingException mex) {
            supportsIdle = false;
        }
        for (;;) {
            if (supportsIdle && folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
                System.out.println("IDLE done");
            } else {
                Thread.sleep(freq); // sleep for freq milliseconds

                // This is to force the IMAP server to send us
                // EXISTS notifications. 
                folder.getMessageCount();
            }
        }

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

From source file:copier.java

public static void main(String argv[]) {
    boolean debug = false; // change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;/*from   w w  w.ja v  a 2 s  .co m*/
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed 
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination, 
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

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

    System.exit(0);
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default 
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // //from   ww w  .java  2 s  . c  om
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is an
        // Oracle SMTP transport configured by 
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Oracle")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();//from   www . j a  v  a 2s.  co m
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);//from w ww. j av a2  s  . c o  m
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        mbp2.attachFile(filename);

        /*
         * Use the following approach instead of the above line if
         * you want to control the MIME type of the attached file.
         * Normally you should never need to do this.
         *
        FileDataSource fds = new FileDataSource(filename) {
        public String getContentType() {
           return "application/octet-stream";
        }
        };
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());
         */

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        /*
         * If you want to control the Content-Transfer-Encoding
         * of the attached file, do the following.  Normally you
         * should never need to do this.
         *
        msg.saveChanges();
        mbp2.setHeader("Content-Transfer-Encoding", "base64");
         */

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String argv[]) {
    boolean debug = false;// change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;//  www  .j a  v  a  2  s .c  o m
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements
        // the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination,
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

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

    System.exit(0);
}

From source file:registry.java

public static void main(String[] args) {
    Properties props = new Properties();

    // set smtp and imap to be our default
    // transport and store protocols, respectively
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.store.protocol", "imap");

    // //from w w  w.j  a  v  a  2s.c om
    props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");

    Session session = Session.getInstance(props, null);
    // session.setDebug(true);

    // Retrieve all configured providers from the Session
    System.out.println("\n------ getProviders()----------");
    Provider[] providers = session.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("** " + providers[i]);

        // let's remember some providers so that we can use them later
        // (I'm explicitly showing multiple ways of testing Providers)
        // BTW, no Provider "ACME Corp" will be found in the default
        // setup b/c its not in any javamail.providers resource files
        String s = null;
        if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) {
            _aProvider = providers[i];
        }

        // this Provider won't be found by default either
        if (providers[i].getClassName().endsWith("application.smtp"))
            _bProvider = providers[i];

        // this Provider will be found since com.sun.mail.imap.IMAPStore
        // is configured in javamail.default.providers
        if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) {
            _sunIMAP = providers[i];
        }

        // this Provider will be found as well since there is a
        // Sun Microsystems SMTP transport configured by
        // default in javamail.default.providers
        if (((s = providers[i].getVendor()) != null) && s.startsWith("Sun Microsystems")
                && providers[i].getType() == Provider.Type.TRANSPORT
                && providers[i].getProtocol().equalsIgnoreCase("smtp")) {
            _sunSMTP = providers[i];
        }
    }

    System.out.println("\n------ initial protocol defaults -------");
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
        // the NNTP provider will fail since we don't have one configured
        System.out.println("nntp: " + session.getProvider("nntp"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> This exception is OK since there is no NNTP Provider configured by default");
        mex.printStackTrace();
    }

    System.out.println("\n------ set new protocol defaults ------");
    // set some new defaults
    try {
        // since _aProvider isn't configured, this will fail
        session.setProvider(_aProvider); // will fail
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: _aProvider is null");
        mex.printStackTrace();
    }
    try {
        // _sunIMAP provider should've configured correctly; should work
        session.setProvider(_sunIMAP);
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }
    try {
        System.out.println("imap: " + session.getProvider("imap"));
        System.out.println("smtp: " + session.getProvider("smtp"));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    System.out.println("\n\n----- get some stores ---------");
    // multiple ways to retrieve stores. these will print out the
    // string "imap:" since its the URLName for the store
    try {
        System.out.println("getStore(): " + session.getStore());
        System.out.println("getStore(Provider): " + session.getStore(_sunIMAP));
    } catch (NoSuchProviderException mex) {
        mex.printStackTrace();
    }

    try {
        System.out.println("getStore(imap): " + session.getStore("imap"));
        // pop3 will fail since it doesn't exist
        System.out.println("getStore(pop3): " + session.getStore("pop3"));
    } catch (NoSuchProviderException mex) {
        System.out.println(">> Exception expected: no pop3 provider");
        mex.printStackTrace();
    }

    System.out.println("\n\n----- now for transports/addresses ---------");
    // retrieve transports; these will print out "smtp:" (like stores did)
    try {
        System.out.println("getTransport(): " + session.getTransport());
        System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP));
        System.out.println("getTransport(smtp): " + session.getTransport("smtp"));
        System.out.println(
                "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon")));
        // News will fail since there's no news provider configured
        System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor")));
    } catch (MessagingException mex) {
        System.out.println(">> Exception expected: no news provider configured");
        mex.printStackTrace();
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);/*from   w  w w .  j a v  a  2  s.  c  o m*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();//from   www .ja  v  a2  s.c  om
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(args[0]) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}