Example usage for javax.mail.internet InternetAddress InternetAddress

List of usage examples for javax.mail.internet InternetAddress InternetAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress InternetAddress.

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:smtpsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from  w w  w .  j a v  a 2 s . c o m
    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;
    boolean ssl = 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("-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")) {
            ssl = true;
        } 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 {
        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();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");

        // 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);

        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(ssl ? "smtps" : "smtp");
        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.");

        // 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) {
        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: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  . ja  v  a  2s  .  c o m
    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: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 2 s.  c o  m
    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: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   ww w .  jav a2 s.  c  o  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:SendApp.java

public static void send(String smtpHost, int smtpPort, String from, String to, String subject, String content)
        throws AddressException, MessagingException {

    java.util.Properties props = new java.util.Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", "" + smtpPort);
    Session session = Session.getDefaultInstance(props, null);

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);/*from w  ww . j a v a2 s  .  c o  m*/
    msg.setText(content);

    Transport.send(msg);
}

From source file:Main.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//  w w w  .  j  a v  a2 s . c  o m
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmail(String to, String from, String subject, String bodyText)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
}

From source file:SendMailBean.java

public void emailPassword(String email, String memberName, String password) {
    String host = "mail";
    String from = "w@j.com";

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    try {//from w ww  .ja  v  a  2 s . c  om
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        message.setSubject("Password Reminder");

        message.setText("Hi " + memberName + ",\nYour password is: " + password + "\nregards - " + from);
        Transport.send(message);
    } catch (AddressException ae) {
    } catch (MessagingException me) {
    }
}

From source file:com.muleinaction.GreenMailUtilities.java

public static MimeMessage toMessage(String text, String email) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setContent(text, "text/plain");
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
    return message;
}

From source file:com.email.SendEmailNotification.java

/**
 * This sends a basic notification email that is just pure TEXT. Message is
 * sent from the section gathered/*from ww w.j  a  v a2 s  .c  o m*/
 *
 * @param eml DocketNotificationModel
 */
public static void sendNotificationEmail(DocketNotificationModel eml) {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getSendTo() == null) ? "".split(";") : eml.getSendTo().split(";"));
        String subject = eml.getMessageSubject();
        String body = eml.getMessageBody();

        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);

        Session session = Session.getInstance(properties, auth);
        MimeMessage email = new MimeMessage(session);

        try {
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            if (Global.isOkToSendEmail()) {
                Transport.send(email);
            } else {
                Audit.addAuditEntry("Notification Not Actually Sent: " + eml.getId() + " - " + subject);
            }

            DocketNotification.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:arena.mail.MailAddressUtils.java

/**
 * Builds a list of internet address objects by parsing the
 * address list of the form "name <email>, name <email>"
 */// w  w w . j  a v  a2 s . c o  m
public static InternetAddress[] parseAddressList(String addressList, String delim, String encoding) {
    if ((addressList == null) || (addressList.trim().length() == 0)) {
        return new InternetAddress[0];
    }
    Log log = LogFactory.getLog(MailAddressUtils.class);
    log.debug("Address list for parsing: " + addressList);
    StringTokenizer st = new StringTokenizer(addressList.trim(), delim);
    List<InternetAddress> addresses = new ArrayList<InternetAddress>();

    for (int n = 0; st.hasMoreTokens(); n++) {
        String fullAddress = st.nextToken().trim();
        if (fullAddress.equals("")) {
            continue;
        }

        try {
            int openPos = fullAddress.indexOf('<');
            int closePos = fullAddress.indexOf('>');

            if (openPos == -1) {
                addresses.add(new InternetAddress(
                        (closePos == -1) ? fullAddress.trim() : fullAddress.substring(0, closePos).trim()));
            } else if (closePos == -1) {
                addresses.add(new InternetAddress(fullAddress.substring(openPos + 1).trim(),
                        fullAddress.substring(0, openPos).trim(), encoding));
            } else {
                addresses.add(new InternetAddress(fullAddress.substring(openPos + 1, closePos).trim(),
                        fullAddress.substring(0, openPos).trim(), encoding));
            }
        } catch (Throwable err) {
            throw new RuntimeException("Error parsing address: " + fullAddress, err);
        }
    }

    log.debug("Found mail addresses: " + addresses);

    return (InternetAddress[]) addresses.toArray(new InternetAddress[addresses.size()]);
}