Example usage for javax.mail MessagingException getNextException

List of usage examples for javax.mail MessagingException getNextException

Introduction

In this page you can find the example usage for javax.mail MessagingException getNextException.

Prototype

public synchronized Exception getNextException() 

Source Link

Document

Get the next exception chained to this one.

Usage

From source file:at.molindo.notify.channel.mail.DirectMailClient.java

@Override
protected String toErrorMessage(MessagingException e) {
    if (e instanceof SendFailedException) {
        if (e.getNextException() instanceof SMTPSendFailedException) {
            final SMTPSendFailedException se = (SMTPSendFailedException) e.getNextException();
            return se.getCommand() + " failed " + " with " + se.getReturnCode() + " (" + e.getMessage() + ")";
        } else if (e.getNextException() instanceof SMTPAddressFailedException) {
            // copied from above, as there is no common base class but same
            // methods
            final SMTPAddressFailedException se = (SMTPAddressFailedException) e.getNextException();
            return se.getCommand() + " failed " + " with " + se.getReturnCode() + " (" + e.getMessage() + ")";
        } else {//from w ww.  j  a v a 2 s .  c  om
            final StringBuilder buf = new StringBuilder();
            Address[] addresses = ((SendFailedException) e).getInvalidAddresses();
            if (addresses != null) {
                for (final Address a : addresses) {
                    buf.append(a).append(" ");
                }
            }
            return "invalied address(es): " + buf + "(" + ExceptionUtils.getAllMessages(e) + ")";
        }
    } else {
        return super.toErrorMessage(e);
    }
}

From source file:com.sammyun.controller.console.SettingController.java

/**
 * //from   w  w  w . j  a  va  2s  .co m
 */
@RequestMapping(value = "/mail_test", method = RequestMethod.POST)
public @ResponseBody Message mailTest(String smtpFromMail, String smtpHost, Integer smtpPort,
        String smtpUsername, String smtpPassword, String toMail) {
    if (StringUtils.isEmpty(toMail)) {
        return ERROR_MESSAGE;
    }
    Setting setting = SettingUtils.get();
    if (StringUtils.isEmpty(smtpPassword)) {
        // smtpPassword = setting.getSmtpPassword();
    }
    try {
        if (!isValid(Setting.class, "smtpFromMail", smtpFromMail)
                || !isValid(Setting.class, "smtpHost", smtpHost)
                || !isValid(Setting.class, "smtpPort", smtpPort)
                || !isValid(Setting.class, "smtpUsername", smtpUsername)) {
            return ERROR_MESSAGE;
        }
    } catch (MailSendException e) {
        Exception[] messageExceptions = e.getMessageExceptions();
        if (messageExceptions != null) {
            for (Exception exception : messageExceptions) {
                if (exception instanceof SMTPSendFailedException) {
                    SMTPSendFailedException smtpSendFailedException = (SMTPSendFailedException) exception;
                    Exception nextException = smtpSendFailedException.getNextException();
                    if (nextException instanceof SMTPSenderFailedException) {
                        return Message.error("console.setting.mailTestSenderFailed");
                    }
                } else if (exception instanceof MessagingException) {
                    MessagingException messagingException = (MessagingException) exception;
                    Exception nextException = messagingException.getNextException();
                    if (nextException instanceof UnknownHostException) {
                        return Message.error("console.setting.mailTestUnknownHost");
                    } else if (nextException instanceof ConnectException) {
                        return Message.error("console.setting.mailTestConnect");
                    }
                }
            }
        }
        return Message.error("console.setting.mailTestError");
    } catch (MailAuthenticationException e) {
        return Message.error("console.setting.mailTestAuthentication");
    } catch (Exception e) {
        return Message.error("console.setting.mailTestError");
    }
    return Message.success("admin.setting.mailTestSuccess");
}

From source file:net.groupbuy.controller.admin.SettingController.java

/**
 * /*from w  w w.j a va2s. c om*/
 */
@RequestMapping(value = "/mail_test", method = RequestMethod.POST)
public @ResponseBody Message mailTest(String smtpFromMail, String smtpHost, Integer smtpPort,
        String smtpUsername, String smtpPassword, String toMail) {
    if (StringUtils.isEmpty(toMail)) {
        return ERROR_MESSAGE;
    }
    Setting setting = SettingUtils.get();
    if (StringUtils.isEmpty(smtpPassword)) {
        smtpPassword = setting.getSmtpPassword();
    }
    try {
        if (!isValid(Setting.class, "smtpFromMail", smtpFromMail)
                || !isValid(Setting.class, "smtpHost", smtpHost)
                || !isValid(Setting.class, "smtpPort", smtpPort)
                || !isValid(Setting.class, "smtpUsername", smtpUsername)) {
            return ERROR_MESSAGE;
        }
        mailService.sendTestMail(smtpFromMail, smtpHost, smtpPort, smtpUsername, smtpPassword, toMail);
    } catch (MailSendException e) {
        Exception[] messageExceptions = e.getMessageExceptions();
        if (messageExceptions != null) {
            for (Exception exception : messageExceptions) {
                if (exception instanceof SMTPSendFailedException) {
                    SMTPSendFailedException smtpSendFailedException = (SMTPSendFailedException) exception;
                    Exception nextException = smtpSendFailedException.getNextException();
                    if (nextException instanceof SMTPSenderFailedException) {
                        return Message.error("admin.setting.mailTestSenderFailed");
                    }
                } else if (exception instanceof MessagingException) {
                    MessagingException messagingException = (MessagingException) exception;
                    Exception nextException = messagingException.getNextException();
                    if (nextException instanceof UnknownHostException) {
                        return Message.error("admin.setting.mailTestUnknownHost");
                    } else if (nextException instanceof ConnectException) {
                        return Message.error("admin.setting.mailTestConnect");
                    }
                }
            }
        }
        return Message.error("admin.setting.mailTestError");
    } catch (MailAuthenticationException e) {
        return Message.error("admin.setting.mailTestAuthentication");
    } catch (Exception e) {
        return Message.error("admin.setting.mailTestError");
    }
    return Message.success("admin.setting.mailTestSuccess");
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from   ww  w.j a va2s  . c om*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

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

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            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);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

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

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:TestOpenMailRelay.java

/** Do the work: send the mail to the SMTP server.  */
public void doSend() {

    // We need to pass info to the mail server as a Properties, since
    // JavaMail (wisely) allows room for LOTS of properties...
    Properties props = new Properties();

    // Your LAN must define the local SMTP server as "mailhost"
    // for this simple-minded version to be able to send mail...
    props.put("mail.smtp.host", "mailhost");

    // Create the Session object
    session = Session.getDefaultInstance(props, null);
    session.setDebug(true); // Verbose!

    try {/*from w  w  w. ja v  a2s  .co  m*/
        // create a message
        mesg = new MimeMessage(session);

        // From Address - this should come from a Properties...
        mesg.setFrom(new InternetAddress("nobody@host.domain"));

        // TO Address 
        InternetAddress toAddress = new InternetAddress(message_recip);
        mesg.addRecipient(Message.RecipientType.TO, toAddress);

        // CC Address
        InternetAddress ccAddress = new InternetAddress(message_cc);
        mesg.addRecipient(Message.RecipientType.CC, ccAddress);

        // The Subject
        mesg.setSubject(message_subject);

        // Now the message body.
        mesg.setText(message_body);
        // XXX I18N: use setText(msgText.getText(), charset)

        // Finally, send the message!
        Transport.send(mesg);

    } catch (MessagingException ex) {
        while ((ex = (MessagingException) ex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:com.hs.mail.mailet.RemoteDelivery.java

/**
 * We arranged that the recipients are all going to the same mail server. We
 * will now rely on the DNS server to do DNS MX record lookup and try to
 * deliver to the multiple mail servers. If it fails, we should decide that
 * the failure is permanent or temporary.
 * //from  ww w .j av  a 2s . c  o  m
 * @param host
 *            the same host of recipients
 * @param recipients
 *            recipients who are all going to the same mail server
 * @param message
 *            Mail object to be delivered
 * @param mimemsg
 *            MIME message representation of the message
 * @return true if the delivery was successful or permanent failure so the
 *         message should be deleted, otherwise false and the message will
 *         be tried to send again later
 */
private boolean deliver(String host, Collection<Recipient> recipients, SmtpMessage message,
        MimeMessage mimemsg) {
    // Prepare javamail recipients
    InternetAddress[] addresses = new InternetAddress[recipients.size()];
    Iterator<Recipient> it = recipients.iterator();
    for (int i = 0; it.hasNext(); i++) {
        Recipient rcpt = it.next();
        addresses[i] = rcpt.toInternetAddress();
    }

    try {
        // Lookup the possible targets
        Iterator<HostAddress> targetServers = null;
        if (null == gateway) {
            targetServers = getSmtpHostAddresses(host);
        } else {
            targetServers = getGatewaySmtpHostAddresses(gateway);
        }
        if (!targetServers.hasNext()) {
            logger.info("No mail server found for: " + host);
            StringBuilder exceptionBuffer = new StringBuilder(128)
                    .append("There are no DNS entries for the hostname ").append(host)
                    .append(".  I cannot determine where to send this message.");
            return failMessage(message, addresses, new MessagingException(exceptionBuffer.toString()), false);
        }

        Properties props = session.getProperties();
        if (message.isNotificationMessage()) {
            props.put("mail.smtp.from", "<>");
        } else {
            props.put("mail.smtp.from", message.getFrom().getMailbox());
        }

        MessagingException lastError = null;
        StringBuilder logBuffer = null;
        HostAddress outgoingMailServer = null;
        while (targetServers.hasNext()) {
            try {
                outgoingMailServer = targetServers.next();
                logBuffer = new StringBuilder(256).append("Attempting to deliver message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                Transport transport = null;
                try {
                    transport = session.getTransport(outgoingMailServer);
                    try {
                        if (authUser != null) {
                            transport.connect(outgoingMailServer.getHostName(), authUser, authPass);
                        } else {
                            transport.connect();
                        }
                    } catch (MessagingException e) {
                        // Any error on connect should cause the mailet to
                        // attempt to connect to the next SMTP server
                        // associated with this MX record.
                        logger.error(e.getMessage());
                        continue;
                    }
                    transport.sendMessage(mimemsg, addresses);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (MessagingException e) {
                        }
                        transport = null;
                    }
                }
                logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                        .append(outgoingMailServer.getHostName()).append(" at ")
                        .append(outgoingMailServer.getHost()).append(" for addresses ")
                        .append(Arrays.asList(addresses));
                logger.info(logBuffer.toString());
                recipients.clear();
                return true;
            } catch (SendFailedException sfe) {
                if (sfe.getValidSentAddresses() != null) {
                    Address[] validSent = sfe.getValidSentAddresses();
                    if (validSent.length > 0) {
                        logBuffer = new StringBuilder(256).append("Successfully sent message to host ")
                                .append(outgoingMailServer.getHostName()).append(" at ")
                                .append(outgoingMailServer.getHost()).append(" for addresses ")
                                .append(Arrays.asList(validSent));
                        logger.info(logBuffer.toString());
                        // Remove the addresses to which this message was
                        // sent successfully
                        List<InternetAddress> temp = new ArrayList<InternetAddress>();
                        for (int i = 0; i < addresses.length; i++) {
                            if (!ArrayUtils.contains(validSent, addresses[i])) {
                                if (addresses[i] != null) {
                                    temp.add(addresses[i]);
                                }
                            }
                        }
                        addresses = temp.toArray(new InternetAddress[temp.size()]);
                        removeAll(recipients, validSent);
                    }
                }

                if (sfe instanceof SMTPSendFailedException) {
                    SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                    // If permanent error 5xx, terminate this delivery
                    // attempt by re-throwing the exception
                    if (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599)
                        throw sfe;
                }

                if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
                    // Valid addresses remained, so continue with any other server.
                    if (logger.isDebugEnabled())
                        logger.debug("Send failed, " + sfe.getValidUnsentAddresses().length
                                + " valid recipients(" + Arrays.asList(sfe.getValidUnsentAddresses())
                                + ") remain, continuing with any other servers");
                    lastError = sfe;
                    continue;
                } else {
                    // There are no valid addresses left to send, so re-throw
                    throw sfe;
                }
            } catch (MessagingException me) {
                Exception ne;
                if ((ne = me.getNextException()) != null && ne instanceof IOException) {
                    // It can be some socket or weird I/O related problem.
                    lastError = me;
                    continue;
                }
                throw me;
            }
        } // end while
        if (lastError != null) {
            throw lastError;
        }
    } catch (SendFailedException sfe) {
        boolean deleteMessage = false;

        if (sfe instanceof SMTPSendFailedException) {
            SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
            deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
        } else {
            // Sometimes we'll get a normal SendFailedException with nested
            // SMTPAddressFailedException, so use the latter RetCode
            MessagingException me = sfe;
            Exception ne;
            while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
                me = (MessagingException) ne;
                if (me instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) me;
                    deleteMessage = (ssfe.getReturnCode() >= 500 && ssfe.getReturnCode() <= 599);
                }
            }
        }
        if (!ArrayUtils.isEmpty(sfe.getInvalidAddresses())) {
            // Invalid addresses should be considered permanent
            Address[] invalid = sfe.getInvalidAddresses();
            removeAll(recipients, invalid);
            deleteMessage = failMessage(message, invalid, sfe, true);
        }
        if (!ArrayUtils.isEmpty(sfe.getValidUnsentAddresses())) {
            // Vaild-unsent addresses should be considered temporary
            deleteMessage = failMessage(message, sfe.getValidUnsentAddresses(), sfe, false);
        }
        return deleteMessage;
    } catch (MessagingException mex) {
        // Check whether this is a permanent error (like account doesn't
        // exist or mailbox is full or domain is setup wrong)
        // We fail permanently if this was 5xx error.
        return failMessage(message, addresses, mex, ('5' == mex.getMessage().charAt(0)));
    }
    // If we get here, we've exhausted the loop of servers without sending
    // the message or throwing an exception.
    // One case where this might happen is if there is no server we can
    // connect. So this should be considered temporary
    return failMessage(message, addresses, new MessagingException("No mail server(s) available at this time."),
            false);
}

From source file:com.hs.mail.mailet.RemoteDelivery.java

/**
 * Build error message from the exception.
 *//*from w  ww.  j  a  v  a2 s.  c  om*/
private String buildErrorMessage(Address[] addresses, MessagingException ex) {
    StringBuilder errorBuffer = new StringBuilder();
    if (!ArrayUtils.isEmpty(addresses)) {
        for (int i = 0; i < addresses.length; i++) {
            errorBuffer.append(addresses[i].toString()).append("\r\n");
        }
    }
    Exception ne = ex.getNextException();
    if (ne == null) {
        errorBuffer.append(ex.getMessage().trim());
    } else if (ne instanceof SendFailedException) {
        errorBuffer.append("Remote server told me: " + ne.getMessage().trim());
    } else if (ne instanceof UnknownHostException) {
        errorBuffer.append("Unknown host: " + ne.getMessage().trim());
    } else if (ne instanceof ConnectException) {
        // Already formatted as "Connection timed out: connect"
        errorBuffer.append(ne.getMessage().trim());
    } else if (ne instanceof SocketException) {
        errorBuffer.append("Socket exception: " + ne.getMessage().trim());
    } else {
        errorBuffer.append(ne.getMessage().trim());
    }
    errorBuffer.append("\r\n");
    return errorBuffer.toString();
}

From source file:org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor.java

private void parseConfiguration() throws MessagingException, ConfigurationException {

    // load composite matchers if there are any
    Map<String, Matcher> compositeMatchers = new HashMap<String, Matcher>();
    loadCompositeMatchers(getState(), compositeMatchers, config.configurationsAt("matcher"));

    final List<HierarchicalConfiguration> mailetConfs = config.configurationsAt("mailet");

    // Loop through the mailet configuration, load
    // all of the matcher and mailets, and add
    // them to the processor.
    for (HierarchicalConfiguration c : mailetConfs) {
        // We need to set this because of correctly parsing comma
        String mailetClassName = c.getString("[@class]");
        String matcherName = c.getString("[@match]", null);
        String invertedMatcherName = c.getString("[@notmatch]", null);

        Mailet mailet;//from  www. j ava  2 s  .c o  m
        Matcher matcher;

        try {

            if (matcherName != null && invertedMatcherName != null) {
                // if no matcher is configured throw an Exception
                throw new ConfigurationException("Please configure only match or nomatch per mailet");
            } else if (matcherName != null) {
                // try to load from compositeMatchers first
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(matcherName));
                }
            } else if (invertedMatcherName != null) {
                // try to load from compositeMatchers first
                // matcherName is a known null value at this state
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(invertedMatcherName));
                }
                matcher = new MatcherInverter(matcher);

            } else {
                // default matcher is All
                matcher = matcherLoader.getMatcher(createMatcherConfig("All"));
            }

            // The matcher itself should log that it's been inited.
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Matcher " + matcherName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init matcher " + matcherName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init matcher " + matcherName, ex);
        }
        try {
            mailet = mailetLoader.getMailet(createMailetConfig(mailetClassName, c));
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Mailet " + mailetClassName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init mailet " + mailetClassName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init mailet " + mailetClassName, ex);
        }

        if (matcher != null && mailet != null) {
            pairs.add(new MatcherMailetPair(matcher, mailet));
        } else {
            throw new ConfigurationException("Unable to load Mailet or Matcher");
        }
    }
}

From source file:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * We can assume that the recipients of this message are all going to the
 * same mail server. We will now rely on the JNDI to do DNS MX record lookup
 * and try to deliver to the multiple mail servers. If it fails, it should
 * throw an exception.//  w ww .  ja v  a 2s  .  com
 * 
 * Creation date: (2/24/00 11:25:00 PM)
 * 
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param session
 *            javax.mail.Session
 * @return boolean Whether the delivery was successful and the message can
 *         be deleted
 */
private boolean deliver(QuedItem qi, Session session) {
    MailAddress rcpt = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)");
        }
        MailImpl mail = (MailImpl) qi.getMail();
        MimeMessage message = mail.getMessage();
        // Create an array of the recipients as InternetAddress objects
        Collection recipients = mail.getRecipients();
        InternetAddress addr[] = new InternetAddress[recipients.size()];
        int j = 0;
        // funky ass look because you can't getElementAt() in a Collection

        for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
            MailAddress currentRcpt = (MailAddress) i.next();
            addr[j] = currentRcpt.toInternetAddress();
        }
        if (addr.length <= 0) {
            if (log.isDebugEnabled()) {
                log.debug("No recipients specified... returning");
            }
            return true;
        }
        // Figure out which servers to try to send to. This collection
        // will hold all the possible target servers
        Collection targetServers = null;
        Iterator it = recipients.iterator();
        while (it.hasNext()) {
            rcpt = (MailAddress) recipients.iterator().next();
            if (!qi.recepientHasBeenHandled(rcpt)) {
                break;
            }
        }
        // theoretically it is possible to not hav eone that hasn't been
        // handled
        // however that's only if something has gone really wrong.
        if (rcpt != null) {
            String host = rcpt.getHost();
            // Lookup the possible targets
            try {
                // targetServers = MXLookup.urlsForHost(host); // farking
                // unreliable jndi bs
                targetServers = getMXRecordsForHost(host);
            } catch (Exception e) {
                log.error(e);
            }
            if (targetServers == null || targetServers.size() == 0) {
                log.warn("No mail server found for: " + host);
                StringBuffer exceptionBuffer = new StringBuffer(128)
                        .append("I found no MX record entries for the hostname ").append(host)
                        .append(".  I cannot determine where to send this message.");
                return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true);
            } else if (log.isTraceEnabled()) {
                log.trace(targetServers.size() + " servers found for " + host);
            }
            MessagingException lastError = null;
            Iterator i = targetServers.iterator();
            while (i.hasNext()) {
                try {
                    URLName outgoingMailServer = (URLName) i.next();
                    StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ")
                            .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString())
                            .append(" to addresses ").append(Arrays.asList(addr));
                    if (log.isDebugEnabled()) {
                        log.debug(logMessageBuffer.toString());
                    }
                    ;
                    // URLName urlname = new URLName("smtp://"
                    // + outgoingMailServer);
                    Properties props = session.getProperties();
                    if (mail.getSender() == null) {
                        props.put("mail.smtp.from", "<>");
                    } else {
                        String sender = mail.getSender().toString();
                        props.put("mail.smtp.from", sender);
                    }
                    // Many of these properties are only in later JavaMail
                    // versions
                    // "mail.smtp.ehlo" //default true
                    // "mail.smtp.auth" //default false
                    // "mail.smtp.dsn.ret" //default to nothing... appended
                    // as
                    // RET= after MAIL FROM line.
                    // "mail.smtp.dsn.notify" //default to
                    // nothing...appended as
                    // NOTIFY= after RCPT TO line.
                    Transport transport = null;
                    try {
                        transport = session.getTransport(outgoingMailServer);
                        try {
                            transport.connect();
                        } catch (MessagingException me) {
                            log.error(me);
                            // Any error on connect should cause the mailet
                            // to
                            // attempt
                            // to connect to the next SMTP server associated
                            // with this MX record,
                            // assuming the number of retries hasn't been
                            // exceeded.
                            if (failMessage(qi, rcpt, me, false)) {
                                return true;
                            } else {
                                continue;
                            }
                        }
                        transport.sendMessage(message, addr);
                        // log.debug("message sent to " +addr);
                        /*TODO: catch failures that should result 
                         * in failure with no retries
                         } catch (SendFailedException sfe){
                           qi.failForRecipient(que, );
                           */
                    } finally {
                        if (transport != null) {
                            transport.close();
                            transport = null;
                        }
                    }
                    logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName())
                            .append(") sent successfully to ").append(outgoingMailServer);
                    log.debug(logMessageBuffer.toString());
                    qi.succeededForRecipient(que, rcpt);
                    return true;
                } catch (MessagingException me) {
                    log.error(me);
                    // MessagingException are horribly difficult to figure
                    // out
                    // what actually happened.
                    StringBuffer exceptionBuffer = new StringBuffer(256)
                            .append("Exception delivering message (").append(mail.getName()).append(") - ")
                            .append(me.getMessage());
                    log.warn(exceptionBuffer.toString());
                    if ((me.getNextException() != null)
                            && (me.getNextException() instanceof java.io.IOException)) {
                        // This is more than likely a temporary failure
                        // If it's an IO exception with no nested exception,
                        // it's probably
                        // some socket or weird I/O related problem.
                        lastError = me;
                        continue;
                    }
                    // This was not a connection or I/O error particular to
                    // one
                    // SMTP server of an MX set. Instead, it is almost
                    // certainly
                    // a protocol level error. In this case we assume that
                    // this
                    // is an error we'd encounter with any of the SMTP
                    // servers
                    // associated with this MX record, and we pass the
                    // exception
                    // to the code in the outer block that determines its
                    // severity.
                    throw me;
                } // end catch
            } // end while
              // If we encountered an exception while looping through,
              // throw the last MessagingException we caught. We only
              // do this if we were unable to send the message to any
              // server. If sending eventually succeeded, we exit
              // deliver() though the return at the end of the try
              // block.
            if (lastError != null) {
                throw lastError;
            }
        } // END if (rcpt != null)
        else {
            log.error("unable to find recipient that handn't already been handled");
        }
    } catch (SendFailedException sfe) {
        log.error(sfe);
        boolean deleteMessage = false;
        Collection recipients = qi.getMail().getRecipients();
        // Would like to log all the types of email addresses
        if (log.isDebugEnabled()) {
            log.debug("Recipients: " + recipients);
        }
        /*
         * The rest of the recipients failed for one reason or another.
         * 
         * SendFailedException actually handles this for us. For example, if
         * you send a message that has multiple invalid addresses, you'll
         * get a top-level SendFailedException that that has the valid,
         * valid-unsent, and invalid address lists, with all of the server
         * response messages will be contained within the nested exceptions.
         * [Note: the content of the nested exceptions is implementation
         * dependent.]
         * 
         * sfe.getInvalidAddresses() should be considered permanent.
         * sfe.getValidUnsentAddresses() should be considered temporary.
         * 
         * JavaMail v1.3 properly populates those collections based upon the
         * 4xx and 5xx response codes.
         * 
         */
        if (sfe.getInvalidAddresses() != null) {
            Address[] address = sfe.getInvalidAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse invalid address: " + pe.getMessage());
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Invalid recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, true);
            }
        }
        if (sfe.getValidUnsentAddresses() != null) {
            Address[] address = sfe.getValidUnsentAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse unsent address: " + pe.getMessage());
                        }
                        pe.printStackTrace();
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unsent recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, false);
            }
        }
        return deleteMessage;
    } catch (MessagingException ex) {
        log.error(ex);
        // We should do a better job checking this... if the failure is a
        // general
        // connect exception, this is less descriptive than more specific
        // SMTP command
        // failure... have to lookup and see what are the various Exception
        // possibilities
        // Unable to deliver message after numerous tries... fail
        // accordingly
        // We check whether this is a 5xx error message, which
        // indicates a permanent failure (like account doesn't exist
        // or mailbox is full or domain is setup wrong).
        // We fail permanently if this was a 5xx error
        return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0)));
    } catch (Throwable t) {
        log.error(t);
    }
    /*
     * If we get here, we've exhausted the loop of servers without sending
     * the message or throwing an exception. One case where this might
     * happen is if we get a MessagingException on each transport.connect(),
     * e.g., if there is only one server and we get a connect exception.
     * Return FALSE to keep run() from deleting the message.
     */
    return false;
}

From source file:org.opencastproject.kernel.mail.SmtpService.java

/**
 * Callback from the OSGi <code>ConfigurationAdmin</code> on configuration changes.
 * /* ww w . j  a va2 s.c o m*/
 * @param properties
 *          the configuration properties
 * @throws ConfigurationException
 *           if configuration fails
 */
@SuppressWarnings("rawtypes")
@Override
public void updated(Dictionary properties) throws ConfigurationException {

    // Read the mail server properties
    mailProperties.clear();

    // Mail transport protocol
    mailTransport = StringUtils.trimToNull((String) properties.get(OPT_MAIL_TRANSPORT));
    if (!("smtp".equals(mailTransport) || "smtps".equals(mailTransport))) {
        if (mailTransport != null)
            logger.warn("'{}' procotol not supported. Reverting to default: '{}'", mailTransport,
                    DEFAULT_MAIL_TRANSPORT);
        mailTransport = DEFAULT_MAIL_TRANSPORT;
        logger.debug("Mail transport protocol defaults to '{}'", mailTransport);
    } else {
        logger.debug("Mail transport protocol is '{}'", mailTransport);
    }
    logger.info("Mail transport protocol is '{}'", mailTransport);
    mailProperties.put(OPT_MAIL_TRANSPORT, mailTransport);

    // The mail host is mandatory
    String propName = OPT_MAIL_PREFIX + mailTransport + OPT_MAIL_HOST_SUFFIX;
    mailHost = StringUtils.trimToNull((String) properties.get(propName));
    if (mailHost == null)
        throw new ConfigurationException(propName, "is not set");
    logger.debug("Mail host is {}", mailHost);
    mailProperties.put(propName, mailHost);

    // Mail port
    propName = OPT_MAIL_PREFIX + mailTransport + OPT_MAIL_PORT_SUFFIX;
    String mailPort = StringUtils.trimToNull((String) properties.get(propName));
    if (mailPort == null) {
        mailPort = DEFAULT_MAIL_PORT;
        logger.debug("Mail server port defaults to '{}'", mailPort);
    } else {
        logger.debug("Mail server port is '{}'", mailPort);
    }
    mailProperties.put(propName, mailPort);

    // TSL over SMTP support
    propName = OPT_MAIL_PREFIX + mailTransport + OPT_MAIL_TLS_ENABLE_SUFFIX;
    String smtpStartTLSStr = StringUtils.trimToNull((String) properties.get(propName));
    boolean smtpStartTLS = Boolean.parseBoolean(smtpStartTLSStr);
    if (smtpStartTLS) {
        mailProperties.put(propName, "true");
        logger.debug("TLS over SMTP is enabled");
    } else {
        logger.debug("TLS over SMTP is disabled");
    }

    // Mail user
    mailUser = StringUtils.trimToNull((String) properties.get(OPT_MAIL_USER));
    if (mailUser != null) {
        mailProperties.put(OPT_MAIL_USER, mailUser);
        logger.debug("Mail user is '{}'", mailUser);
    } else {
        logger.debug("Sending mails to {} without authentication", mailHost);
    }

    // Mail password
    mailPassword = StringUtils.trimToNull((String) properties.get(OPT_MAIL_PASSWORD));
    if (mailPassword != null) {
        mailProperties.put(OPT_MAIL_PASSWORD, mailPassword);
        logger.debug("Mail password set");
    }

    // Mail sender
    String mailFrom = StringUtils.trimToNull((String) properties.get(OPT_MAIL_FROM));
    if (mailFrom == null) {
        logger.debug("Mail sender defaults to {}", mailFrom);
    } else {
        logger.debug("Mail sender is '{}'", mailFrom);
    }
    mailProperties.put(OPT_MAIL_FROM, mailFrom);

    // Authentication
    propName = OPT_MAIL_PREFIX + mailTransport + OPT_MAIL_AUTH_SUFFIX;
    mailProperties.put(propName, Boolean.toString(mailUser != null));

    // Mail debugging
    String mailDebug = StringUtils.trimToNull((String) properties.get(OPT_MAIL_DEBUG));
    if (mailDebug != null) {
        boolean mailDebugEnabled = Boolean.parseBoolean(mailDebug);
        mailProperties.put(OPT_MAIL_DEBUG, Boolean.toString(mailDebugEnabled));
        logger.info("Mail debugging is {}", mailDebugEnabled ? "enabled" : "disabled");
    }

    defaultMailSession = null;
    logger.info("Mail service configured with {}", mailHost);

    Properties props = getSession().getProperties();
    for (String key : props.stringPropertyNames())
        logger.info("{}: {}", key, props.getProperty(key));

    // Test
    String mailTest = StringUtils.trimToNull((String) properties.get(OPT_MAIL_TEST));
    if (mailTest != null && Boolean.parseBoolean(mailTest)) {
        logger.info("Sending test message to {}", mailFrom);
        try {
            sendTestMessage(mailFrom);
        } catch (MessagingException e) {
            logger.error("Error sending test message to " + mailFrom + ": " + e.getMessage());
            while (e.getNextException() != null) {
                Exception ne = e.getNextException();
                logger.error("Error sending test message to " + mailFrom + ": " + ne.getMessage());
                if (ne instanceof MessagingException)
                    e = (MessagingException) ne;
                else
                    break;
            }
            throw new ConfigurationException(OPT_MAIL_PREFIX + mailTransport + OPT_MAIL_HOST_SUFFIX,
                    "Failed to send test message to " + mailFrom);
        }
    }
}