Example usage for javax.mail.internet InternetAddress getLocalAddress

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

Introduction

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

Prototype

public static InternetAddress getLocalAddress(Session session) 

Source Link

Document

Return an InternetAddress object representing the current user.

Usage

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset./*from  w ww .  j  a v a 2  s  .com*/
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

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

public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent)
        throws MessagingException {
    MimeMessage reply = new MimeMessage(account.getMailSession());
    /*//from ww w. j  a v  a 2s . c  o m
     * Have to manipulate the raw Subject header so that we don't lose
     * any encoding information.  This is safe because "Re:" isn't
     * internationalized and (generally) isn't encoded.  If the entire
     * Subject header is encoded, prefixing it with "Re: " still leaves
     * a valid and correct encoded header.
     */
    String subject = orig.getHeader("Subject", null);
    if (subject != null) {
        if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) {
            subject = "Re: " + subject;
        }
        reply.setHeader("Subject", subject);
    }
    Address a[] = null;
    if (!fromSent)
        a = orig.getReplyTo();
    else {
        Address ax[] = orig.getRecipients(RecipientType.TO);
        if (ax != null) {
            a = new Address[1];
            a[0] = ax[0];
        }
    }
    reply.setRecipients(Message.RecipientType.TO, a);
    if (replyToAll) {
        Vector v = new Vector();
        Session session = account.getMailSession();
        // add my own address to list
        InternetAddress me = InternetAddress.getLocalAddress(session);
        if (me != null) {
            v.addElement(me);
        }
        // add any alternate names I'm known by
        String alternates = null;
        if (session != null) {
            alternates = session.getProperty("mail.alternates");
        }
        if (alternates != null) {
            eliminateDuplicates(v, InternetAddress.parse(alternates, false));
        }
        // should we Cc all other original recipients?
        String replyallccStr = null;
        boolean replyallcc = false;
        if (session != null) {
            replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false);
        }
        // add the recipients from the To field so far
        eliminateDuplicates(v, a);
        a = orig.getRecipients(Message.RecipientType.TO);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            if (replyallcc) {
                reply.addRecipients(Message.RecipientType.CC, a);
            } else {
                reply.addRecipients(Message.RecipientType.TO, a);
            }
        }
        a = orig.getRecipients(Message.RecipientType.CC);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            reply.addRecipients(Message.RecipientType.CC, a);
        }
        // don't eliminate duplicate newsgroups
        a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS);
        if (a != null && a.length > 0) {
            reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a);
        }
    }

    String msgId = orig.getHeader("Message-Id", null);
    if (msgId != null) {
        reply.setHeader("In-Reply-To", msgId);
    }

    /*
     * Set the References header as described in RFC 2822:
     *
     * The "References:" field will contain the contents of the parent's
     * "References:" field (if any) followed by the contents of the parent's
     * "Message-ID:" field (if any).  If the parent message does not contain
     * a "References:" field but does have an "In-Reply-To:" field
     * containing a single message identifier, then the "References:" field
     * will contain the contents of the parent's "In-Reply-To:" field
     * followed by the contents of the parent's "Message-ID:" field (if
     * any).  If the parent has none of the "References:", "In-Reply-To:",
     * or "Message-ID:" fields, then the new message will have no
     * "References:" field.
     */
    String refs = orig.getHeader("References", " ");
    if (refs == null) {
        // XXX - should only use if it contains a single message identifier
        refs = orig.getHeader("In-Reply-To", " ");
    }
    if (msgId != null) {
        if (refs != null) {
            refs = MimeUtility.unfold(refs) + " " + msgId;
        } else {
            refs = msgId;
        }
    }
    if (refs != null) {
        reply.setHeader("References", MimeUtility.fold(12, refs));
    }

    //try {
    //    setFlags(answeredFlag, true);
    //} catch (MessagingException mex) {
    //    // ignore it
    //}
    return reply;
}

From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java

/**
 * Send an email to the given email address with the given subject line,
 * using contents generated from the given template and parameters.
 *
 * @param templateName The name of the template used to generate the
 * contents of the email./*from w w w .  ja  va  2 s. com*/
 * @param subject The subject for the email being sent.
 * @param emailAddress Sends the email to this address.
 * @param params The template is merged with these parameters to generate
 * the content of the email.
 * @throws EmailException Thrown if there are any errors in generating
 * content from the template, composing the email, or sending the email.
 */
private void sendMessage(final String templateName, final String subject, final String emailAddress,
        final Map<String, Object> params) throws EmailException {
    Writer stringWriter = new StringWriter();
    try {
        Template template = this.configuration.getTemplate(templateName);
        template.process(params, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new EmailException(e);
    }

    String content = stringWriter.toString();
    MimeMessage message = new MimeMessage(this.session);
    try {
        InternetAddress fromEmailAddress = null;
        String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress();
        if (fromEmailAddressStr != null) {
            fromEmailAddress = new InternetAddress(fromEmailAddressStr);
        }
        if (fromEmailAddress == null) {
            fromEmailAddress = InternetAddress.getLocalAddress(this.session);
        }
        if (fromEmailAddress == null) {
            try {
                fromEmailAddress = new InternetAddress(
                        "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName());
            } catch (UnknownHostException ex) {
                fromEmailAddress = new InternetAddress("no-reply@localhost");
            }
        }
        message.setFrom(fromEmailAddress);
        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
        message.setSender(fromEmailAddress);
        Transport.send(message);
    } catch (MessagingException e) {
        LOGGER.error("Error sending the following email message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            message.writeTo(out);
            out.close();
        } catch (IOException | MessagingException ex) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
        LOGGER.error(out.toString());
        throw new EmailException(e);
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

public static Exchange2003Connection createConnection(String protocol, Session session, String host, int port,
        String username, String password) throws Exception {
    String prefix = "mail." + protocol.toLowerCase() + ".";
    boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY));
    String pwd = (password == null) ? null : debugPassword ? password : "<password>";
    if (host == null || username == null || password == null) {
        if (session.getDebug()) {
            session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username
                    + "\",password=\"" + pwd + "\"");
        }//from   w  ww .  j  a  v a  2 s.c  o  m
        throw new IllegalStateException("Host, username, and password must be specified.");
    }
    boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY));
    /* Mirco */
    String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK);
    String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY);
    String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY);
    String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY);
    boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY));
    boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY));
    int limit = -1;
    String limitString = session.getProperty(LIMIT_PROPERTY);
    if (limitString != null) {
        try {
            limit = Integer.parseInt(limitString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid limit specified: " + limitString);
        }
    }
    try {
        URL url = new URL(host);
        // if parsing succeeded, then strip out the components and use
        secure = "https".equalsIgnoreCase(url.getProtocol());
        host = url.getHost();
        int specifiedPort = url.getPort();
        if (specifiedPort != -1)
            port = specifiedPort;
    } catch (MalformedURLException ex) {
        if (session.getDebug()) {
            session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for "
                    + "secure, host, and port.");
        }
    }
    if (port == -1) {
        try {
            port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY));
        } catch (Exception ignore) {
        }
        if (port == -1)
            port = secure ? HTTPS_PORT : HTTP_PORT;
    }
    String server = (secure ? "https://" : "http://") + host;
    if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) {
        server += ":" + port;
    }
    String mailbox = session.getProperty(MAILBOX_PROPERTY);
    if (mailbox == null) {
        mailbox = session.getProperty(prefix + FROM_PROPERTY);
        if (mailbox == null) {
            mailbox = InternetAddress.getLocalAddress(session).getAddress();
        }
    }

    int index = username.indexOf(':');
    if (index != -1) {
        mailbox = username.substring(index + 1);
        username = username.substring(0, index);
        String mailboxOptions = null;
        index = mailbox.indexOf('[');
        if (index != -1) {
            mailboxOptions = mailbox.substring(index + 1);
            mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']'));
            mailbox = mailbox.substring(0, index);
        }
        if (mailboxOptions != null) {
            Properties props = null;
            try {
                props = parseOptions(mailboxOptions);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex);
            }
            String value = props.getProperty("unfiltered");
            if (value != null)
                unfiltered = Boolean.parseBoolean(value);

            /* Mirco */
            value = props.getProperty("filterLastCheck");
            if (value != null)
                filterLastCheck = value;
            value = props.getProperty("filterTo");
            if (value != null)
                filterTo = value;
            value = props.getProperty("filterFrom");
            if (value != null)
                filterFrom = value;
            value = props.getProperty("filterNotFrom");
            if (value != null)
                filterNotFrom = value;

            value = props.getProperty("delete");
            if (value != null)
                delete = Boolean.parseBoolean(value);
            value = props.getProperty("limit");
            if (value != null) {
                try {
                    limit = Integer.parseInt(value);
                } catch (NumberFormatException ex) {
                    throw new NumberFormatException("Invalid limit specified: " + value);
                }
            }
        } else if (session.getDebug()) {
            session.getDebugOut().println(
                    "No mailbox options specified; " + "using explicit limit, unfiltered, and delete.");
        }
    } else if (session.getDebug()) {
        session.getDebugOut().println("No mailbox specified in username; "
                + "using explicit mailbox, limit, unfiltered, and delete.");
    }
    int timeout = -1;
    String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            timeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid timeout value: " + timeoutString);
        }
    }
    int connectionTimeout = -1;
    timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            connectionTimeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid connection timeout value: " + timeoutString);
        }
    }
    InetAddress localAddress = null;
    String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY);
    if (localAddressString != null) {
        try {
            localAddress = InetAddress.getByName(localAddressString);
        } catch (Exception ex) {
            throw new UnknownHostException("Invalid local address specified: " + localAddressString);
        }
    }
    if (mailbox == null) {
        throw new IllegalStateException("No mailbox specified.");
    }
    if (session.getDebug()) {
        PrintStream debugStream = session.getDebugOut();
        debugStream.println("Server:\t" + server);
        debugStream.println("Username:\t" + username);
        debugStream.println("Password:\t" + pwd);
        debugStream.println("Mailbox:\t" + mailbox);
        debugStream.print("Options:\t");
        debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages");
        debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread");
        debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck"
                : "; Filtered after " + filterLastCheck);
        debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain"
                : "; Filtered from " + filterFrom);
        debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom"
                : "; Filtered not from " + filterNotFrom);
        debugStream.print(
                filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo);
        debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete");
        if (timeout > 0) {
            debugStream.println("Read timeout:\t" + timeout + " ms");
        }
        if (connectionTimeout > 0) {
            debugStream.println("Connection timeout:\t" + connectionTimeout + " ms");
        }
    }
    return new Exchange2003Connection(session, server, mailbox, username, password, timeout, connectionTimeout,
            localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo);
}

From source file:org.exjello.mail.ExchangeConnection.java

public static ExchangeConnection createConnection(String protocol, Session session, String host, int port,
        String username, String password) throws Exception {
    String prefix = "mail." + protocol.toLowerCase() + ".";
    boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY));
    String pwd = (password == null) ? null : debugPassword ? password : "<password>";
    if (host == null || username == null || password == null) {
        if (session.getDebug()) {
            session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username
                    + "\",password=\"" + pwd + "\"");
        }//from  ww  w . j av  a 2s.  c o  m
        throw new IllegalStateException("Host, username, and password must be specified.");
    }
    boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY));
    /* Mirco */
    String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK);
    String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY);
    String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY);
    String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY);
    boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY));
    boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY));
    int limit = -1;
    String limitString = session.getProperty(LIMIT_PROPERTY);
    if (limitString != null) {
        try {
            limit = Integer.parseInt(limitString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid limit specified: " + limitString);
        }
    }
    try {
        URL url = new URL(host);
        // if parsing succeeded, then strip out the components and use
        secure = "https".equalsIgnoreCase(url.getProtocol());
        host = url.getHost();
        int specifiedPort = url.getPort();
        if (specifiedPort != -1)
            port = specifiedPort;
    } catch (MalformedURLException ex) {
        if (session.getDebug()) {
            session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for "
                    + "secure, host, and port.");
        }
    }
    if (port == -1) {
        try {
            port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY));
        } catch (Exception ignore) {
        }
        if (port == -1)
            port = secure ? HTTPS_PORT : HTTP_PORT;
    }
    String server = (secure ? "https://" : "http://") + host;
    if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) {
        server += ":" + port;
    }
    String mailbox = session.getProperty(MAILBOX_PROPERTY);
    if (mailbox == null) {
        mailbox = session.getProperty(prefix + FROM_PROPERTY);
        if (mailbox == null) {
            mailbox = InternetAddress.getLocalAddress(session).getAddress();
        }
    }

    int index = username.indexOf(':');
    if (index != -1) {
        mailbox = username.substring(index + 1);
        username = username.substring(0, index);
        String mailboxOptions = null;
        index = mailbox.indexOf('[');
        if (index != -1) {
            mailboxOptions = mailbox.substring(index + 1);
            mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']'));
            mailbox = mailbox.substring(0, index);
        }
        if (mailboxOptions != null) {
            Properties props = null;
            try {
                props = parseOptions(mailboxOptions);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex);
            }
            String value = props.getProperty("unfiltered");
            if (value != null)
                unfiltered = Boolean.parseBoolean(value);

            /* Mirco */
            value = props.getProperty("filterLastCheck");
            if (value != null)
                filterLastCheck = value;
            value = props.getProperty("filterTo");
            if (value != null)
                filterTo = value;
            value = props.getProperty("filterFrom");
            if (value != null)
                filterFrom = value;
            value = props.getProperty("filterNotFrom");
            if (value != null)
                filterNotFrom = value;

            value = props.getProperty("delete");
            if (value != null)
                delete = Boolean.parseBoolean(value);
            value = props.getProperty("limit");
            if (value != null) {
                try {
                    limit = Integer.parseInt(value);
                } catch (NumberFormatException ex) {
                    throw new NumberFormatException("Invalid limit specified: " + value);
                }
            }
        } else if (session.getDebug()) {
            session.getDebugOut().println(
                    "No mailbox options specified; " + "using explicit limit, unfiltered, and delete.");
        }
    } else if (session.getDebug()) {
        session.getDebugOut().println("No mailbox specified in username; "
                + "using explicit mailbox, limit, unfiltered, and delete.");
    }
    int timeout = -1;
    String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            timeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid timeout value: " + timeoutString);
        }
    }
    int connectionTimeout = -1;
    timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            connectionTimeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid connection timeout value: " + timeoutString);
        }
    }
    InetAddress localAddress = null;
    String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY);
    if (localAddressString != null) {
        try {
            localAddress = InetAddress.getByName(localAddressString);
        } catch (Exception ex) {
            throw new UnknownHostException("Invalid local address specified: " + localAddressString);
        }
    }
    if (mailbox == null) {
        throw new IllegalStateException("No mailbox specified.");
    }
    if (session.getDebug()) {
        PrintStream debugStream = session.getDebugOut();
        debugStream.println("Server:\t" + server);
        debugStream.println("Username:\t" + username);
        debugStream.println("Password:\t" + pwd);
        debugStream.println("Mailbox:\t" + mailbox);
        debugStream.print("Options:\t");
        debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages");
        debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread");
        debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck"
                : "; Filtered after " + filterLastCheck);
        debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain"
                : "; Filtered from " + filterFrom);
        debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom"
                : "; Filtered not from " + filterNotFrom);
        debugStream.print(
                filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo);
        debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete");
        if (timeout > 0) {
            debugStream.println("Read timeout:\t" + timeout + " ms");
        }
        if (connectionTimeout > 0) {
            debugStream.println("Connection timeout:\t" + connectionTimeout + " ms");
        }
    }
    return new ExchangeConnection(session, server, mailbox, username, password, timeout, connectionTimeout,
            localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo);
}

From source file:org.xwiki.watchlist.internal.notification.WatchListEventMimeMessageIterator.java

/**
 * Compute the suffix of a conversation ID. It is done similar to what JavaMail does by default, using the session
 * to extract data (user, host, etc.) that can be set by the client, in case multiple instances of XWiki run on the
 * same machine.//  w  w w.j a  v a  2 s  .co m
 */
private String getConversationSuffix() {
    String suffix = null;

    Session session = this.sessionFactory.create(Collections.<String, String>emptyMap());
    InternetAddress addr = InternetAddress.getLocalAddress(session);
    if (addr != null) {
        suffix = addr.getAddress();
    } else {
        // Worst-case default
        suffix = "xwiki@localhost";
    }

    return suffix;
}