Example usage for org.apache.commons.mail EmailException getCause

List of usage examples for org.apache.commons.mail EmailException getCause

Introduction

In this page you can find the example usage for org.apache.commons.mail EmailException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.commander4j.email.JeMail.java

public void postMail(String recipientsTO[], String subject, String message, String attachmentFilename,
        String attachmentLongFilename) throws MessagingException {

    logger.debug("SMTP_AUTH_REQD=" + SMTP_AUTH_REQD);
    logger.debug("MAIL_SMTP_HOST_NAME=" + SMTP_HOST_NAME);
    logger.debug("MAIL_SMTP_AUTH_USER=" + SMTP_AUTH_USER);
    logger.debug("MAIL_SMTP_AUTH_PWD=********");
    logger.debug("MAIL_SMTP_PORT=" + MAIL_SMTP_PORT);
    logger.debug("MAIL_SMTP_SSL_PORT=" + MAIL_SMTP_SSL_PORT);
    logger.debug("MAIL_SMTP_FROM_ADRESS=" + SMTP_FROM_ADRESS);
    logger.debug("MAIL_SMTP_USE_SSL=" + SMTP_USE_SSL);

    //Email email = new SimpleEmail();
    logger.debug("Creating MultiPart Email");
    MultiPartEmail email = new MultiPartEmail();

    logger.debug("Setting Host Name to " + SMTP_HOST_NAME);
    email.setHostName(SMTP_HOST_NAME);/*from   w ww  . j  a  v  a2s  .  c o  m*/
    logger.debug("Setting SMTP Port to " + MAIL_SMTP_PORT);
    email.setSmtpPort(Integer.valueOf(MAIL_SMTP_PORT));

    logger.debug("Setting SMTP SSL Port to " + MAIL_SMTP_SSL_PORT);
    email.setSslSmtpPort(MAIL_SMTP_SSL_PORT);

    logger.debug("Setting Use SSL on Connect to  " + SMTP_USE_SSL);
    email.setSSLOnConnect(Boolean.valueOf(SMTP_USE_SSL));

    logger.debug("Authentication Required =  " + SMTP_AUTH_REQD);

    if (SMTP_AUTH_REQD.toUpperCase().equals("TRUE")) {
        email.setAuthenticator(new DefaultAuthenticator(SMTP_AUTH_USER, SMTP_AUTH_PWD));

    }

    logger.debug("Setting SMTP USE SSL =  " + SMTP_USE_SSL);
    email.setSSLOnConnect(Boolean.valueOf(SMTP_USE_SSL));

    logger.debug("Setting SMTP USE TLS =  " + SMTP_USE_TLS);
    email.setStartTLSEnabled(Boolean.valueOf(SMTP_USE_TLS));
    email.setStartTLSRequired(Boolean.valueOf(SMTP_USE_TLS));

    try {
        logger.debug("From Address =  " + SMTP_FROM_ADRESS);
        email.setFrom(SMTP_FROM_ADRESS);
        email.setSubject(subject);
        email.setMsg(message + "\n\n");
        for (int x = 1; x <= recipientsTO.length; x++) {
            logger.debug("Add To Address =  " + recipientsTO[x - 1]);
            email.addTo(recipientsTO[x - 1]);
        }

        if (JUtility.replaceNullStringwithBlank(attachmentFilename).equals("") == false) {
            // Create the attachment
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentLongFilename);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription(attachmentFilename);
            attachment.setName(attachmentFilename);

            // add the attachment
            logger.debug("Add Attachment");
            email.attach(attachment);
        }

        logger.debug("Sending");
        email.send();
        logger.debug("Sent successfully");
    } catch (EmailException e) {
        logger.error("Unable to send email : " + e.getCause().getMessage());
    }

}

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aToken/*from w w  w  .  j a v a2s. c  o m*/
 * @return
 */
public Token sendMail(Token aToken) {
    String lFrom = aToken.getString("from", "[unknown]");
    String lTo = aToken.getString("to");
    String lCC = aToken.getString("cc");
    String lBCC = aToken.getString("bcc");
    String lSubject = aToken.getString("subject");
    String lBody = aToken.getString("body");
    Boolean lIsHTML = aToken.getBoolean("html", false);
    List<Object> lAttachedFiles = aToken.getList("attachments");
    String lMsg;

    // instantiate response token
    Token lResponse = TokenFactory.createToken();

    Map<String, String> lMap = new FastMap<String, String>();

    if (lFrom != null && lFrom.length() > 0) {
        lMap.put("from", lFrom);
    }
    if (lTo != null && lTo.length() > 0) {
        lMap.put("to", lTo);
    }
    if (lCC != null && lCC.length() > 0) {
        lMap.put("cc", lCC);
    }
    if (lBCC != null && lBCC.length() > 0) {
        lMap.put("bcc", lBCC);
    }
    if (lSubject != null && lSubject.length() > 0) {
        lMap.put("subject", lSubject);
    }
    if (lBody != null && lBody.length() > 0) {
        lMap.put("body", lBody);
    }

    // Create the attachment
    List<EmailAttachment> lEmailAttachments = new FastList<EmailAttachment>();

    if (lAttachedFiles != null) {
        for (Object lAttachedFile : lAttachedFiles) {
            EmailAttachment lAttachment = new EmailAttachment();
            lAttachment.setPath((String) lAttachedFile);
            lAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            // lAttachment.setDescription( "Picture of John" );
            // lAttachment.setName( "John" );
            lEmailAttachments.add(lAttachment);
        }
    }

    // Create the lEmail message
    if (mLog.isDebugEnabled()) {
        mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'...");
    }
    try {
        Email lEmail;
        if (lIsHTML) {
            lEmail = new HtmlEmail();
        } else {
            lEmail = new MultiPartEmail();
        }

        lEmail.setHostName(mSettings.getSmtpHost());
        lEmail.setSmtpPort(mSettings.getSmtpPort());
        if (mSettings.getSmtpAuth()) {
            lEmail.setAuthentication(mSettings.getSmtpUser(), mSettings.getSmtpPassword());
        }
        if (mSettings.getSmtpPop3Before()) {
            lEmail.setPopBeforeSmtp(true, mSettings.getPop3Host(), mSettings.getPop3User(),
                    mSettings.getPop3Password());
        }
        if (lFrom != null && lFrom.length() > 0) {
            lEmail.setFrom(lFrom);
        }
        if (lTo != null && lTo.length() > 0) {
            String[] lToSplit = lTo.split(";");
            for (String lToSplit1 : lToSplit) {
                if (lToSplit1 != null && lToSplit1.length() > 0) {
                    lEmail.addTo(lToSplit1.trim());
                }
            }
        }
        if (lCC != null && lCC.length() > 0) {
            String[] lCCSplit = lCC.split(";");
            for (String lCCSplit1 : lCCSplit) {
                if (lCCSplit1 != null && lCCSplit1.length() > 0) {
                    lEmail.addCc(lCCSplit1.trim());
                }
            }
        }
        if (lBCC != null && lBCC.length() > 0) {
            String[] lBCCSplit = lBCC.split(";");
            for (String lBCCSplit1 : lBCCSplit) {
                if (lBCCSplit1 != null && lBCCSplit1.length() > 0) {
                    lEmail.addBcc(lBCCSplit1.trim());
                }
            }
        }
        if (lSubject != null && lSubject.length() > 0) {
            lEmail.setSubject(lSubject);
        }

        if (lBody != null && lBody.length() > 0) {
            if (lIsHTML) {
                HtmlEmail lHTML = ((HtmlEmail) lEmail);
                /*
                 * URL lURL = new
                 * URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg");
                 * String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet
                 * further logo");
                 *
                 * //url = new URL(
                 * "http://five-feet-further.com/resources/css/IJX4FWDocu.css"
                 * ); // String css = ((HtmlEmail)lEmail).embed( url, "name
                 * of css" );
                 *
                 * ((HtmlEmail )lEmail).setHtmlMsg( "<html><body>" + "<style
                 * type=\"text/css\">" + "h1 { " + " font-family:arial,
                 * helvetica, sans-serif;" + " font-weight:bold;" + "
                 * font-size:18pt;" + "}" + "</style>" + // "<link
                 * href=\"cid:" + css + "\" type=\"text/css\"
                 * rel=\"stylesheet\">" + "<p><img src=\"cid:" + lCID +
                 * "\"></p>" + "<p><img
                 * src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>"
                 * + lItem + "</body></html>");
                 */

                /*
                 * // Now the message body. Multipart mp = new
                 * MimeMultipart();
                 *
                 * BodyPart textPart = new MimeBodyPart(); // sets type to
                 * "text/plain" textPart.setText("Kann Ihr Browser keine
                 * HTML-Mails darstellen?");
                 *
                 * BodyPart pixPart = new MimeBodyPart();
                 * pixPart.setContent(lMsg, "text/html");
                 *
                 * // Collect the Parts into the MultiPart
                 * mp.addBodyPart(textPart); mp.addBodyPart(pixPart);
                 *
                 * // Put the MultiPart into the Message ((HtmlEmail)
                 * lEmail).setContent((MimeMultipart)mp); ((HtmlEmail)
                 * lEmail).buildMimeMessage();
                 *
                 * /*
                 * // ((HtmlEmail) lEmail).setContent(lMsg,
                 * Email.TEXT_HTML);
                 *
                 * // lHeaders.put("Innotrade-Id", "4711-0815"); //
                 * lHTML.setHeaders(lHeaders); // ((HtmlEmail)
                 * lEmail).setCharset("UTF-8"); // ((HtmlEmail)
                 * lEmail).setMsg(lMsg); lMM.setHeader("Innotrade-Id",
                 * "4711-0815");
                 *
                 * // ((HtmlEmail) lEmail).setContent(lTxtMsg,
                 * Email.TEXT_PLAIN);
                 */
                // String lTxtMsg = "Your Email-Client does not support HTML messages.";
                lHTML.setHtmlMsg(lBody);
                // lHTML.setTextMsg(lTxtMsg);
            } else {
                lEmail.setMsg(lBody);
            }
        }

        // add attachment(s), if such
        for (EmailAttachment lAttachment : lEmailAttachments) {
            ((MultiPartEmail) lEmail).attach(lAttachment);
        }

        // send the Email
        String lMsgId = lEmail.send();

        if (mLog.isInfoEnabled()) {
            lMsg = "Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to "
                    + (lTo != null ? lTo : "(no recipient)") + " cc " + (lCC != null ? lCC : "(no recipient)")
                    + ", subject " + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", msgId "
                    + lMsgId;
            mLog.info(lMsg);
        }
        lResponse.setInteger("code", 0);
        lResponse.setString("msg", "ok");
        lResponse.setString("msgId", lMsgId);
    } catch (EmailException lEx) {
        lMsg = lEx.getClass().getSimpleName() + " (" + lEx.getCause().getClass().getSimpleName() + "): "
                + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }
    return lResponse;
}

From source file:org.opencms.mail.CmsSimpleMail.java

/**
   * Overrides to add a better message for authentication exception.<p>
   * /*from   w  ww  . j  a  v  a  2s .  c  o m*/
   * @see org.apache.commons.mail.Email#send()
   */
@Override
public String send() {

    String messageID = null;
    try {
        messageID = super.send();
    } catch (EmailException e) {
        // check if original Exception is of type SendFailedException which
        // should have been thrown by javax.mail.Transport.send()
        if (e.getCause() instanceof AuthenticationFailedException) {
            CmsMailHost host = OpenCms.getSystemInfo().getMailSettings().getDefaultMailHost();
            // wrong user credentials in opencms-system.xml: mail api does not provide a message for authentication exception

            CmsRuntimeException rte = new CmsRuntimeException(Messages.get()
                    .container(Messages.ERR_SEND_EMAIL_AUTHENTICATE_2, host.getUsername(), host.getHostname()));
            rte.initCause(e);
            throw rte;

        } else {
            CmsRuntimeException rte = new CmsRuntimeException(
                    Messages.get().container(Messages.ERR_SEND_EMAIL_CONFIG_0));
            rte.initCause(e);
            throw rte;
        }
    }
    return messageID;
}

From source file:org.opencms.mail.TestCmsMail.java

/**
 * Tests sending mails to invalid email address.<p>
 *///from  ww w.  j  a va 2  s.  c o  m
public void testCmsInvalidMailAddress() {

    echo("Trying to send an HTML mail to invalid mail address ...");

    String invalidMail = "abc@blockmail.de";
    CmsHtmlMail mail = new CmsHtmlMail();
    StringBuilder sb = new StringBuilder("<html><body>");
    sb.append("<h1>Test mail containing HTML</h1>");
    sb.append("<p>This is only a test mail for sending HTML mails.</p>");
    sb.append(
            "<p><a href=\"http://www.opencms.org/\"><img src=\"http://www.opencms.org/export/system/modules/org.opencms.website.template/resources/img/logo/logo_opencms.gif\" border=\"0\"></a></p>");
    sb.append("<p><a href=\"http://www.opencms.org/\">www.opencms.org</a>");
    sb.append("</body></html>");

    // EmailException will be caught here to test functionality required by
    // CmsMessageInfo.java
    try {
        mail.setHtmlMsg(sb.toString());
        mail.addTo(invalidMail);
        mail.setSubject("OpenCms TestCase HTML Mail");
        mail.setSmtpPort(SMTP_PORT);
        String messageID = mail.send();
        assertNull(messageID);
    } catch (EmailException e) {
        // Check if root cause was SendFailedException due to rejected mail by SMTP server
        assertTrue(e.getCause() instanceof SendFailedException);
        SendFailedException sfe = (SendFailedException) e.getCause();
        Address[] invalidAddresses = sfe.getInvalidAddresses();
        InternetAddress invalidAddress = (InternetAddress) invalidAddresses[0];
        echo("Invalid address was: " + invalidAddress.getAddress());
        assertEquals(invalidMail, invalidAddress.getAddress());
    }
}

From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {// ww w  .j  a  v  a 2 s .c om
        String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
        Object objRcpt = message.getObjectProperty(RECIPIENTS);
        List<String> recipients = null;

        if (objRcpt instanceof List<?>) {
            recipients = (List<String>) objRcpt;
        } else if (objRcpt instanceof String) {
            recipients = new LinkedList<String>();
            String[] rcpts = StringUtils.split((String) objRcpt, ',');
            for (String rcpt : rcpts) {
                recipients.add(rcpt);
            }
        }

        javax.jcr.Session adminSession = repository.loginAdministrative(null);
        ResourceResolver resolver = jcrResourceResolverFactory.getResourceResolver(adminSession);

        Node messageNode = resolver.getResource(nodePath).adaptTo(Node.class);

        if (objRcpt != null) {
            // validate the message
            if (messageNode != null) {
                if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)
                        && MessageConstants.BOX_OUTBOX.equals(
                                messageNode.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX).getString())) {
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                        // We're retrying this message, so clear the errors
                        messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null);
                    }
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_TO)
                            && messageNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
                        // make a commons-email message from the message
                        MultiPartEmail email;
                        try {
                            email = constructMessage(messageNode, recipients);

                            email.setSmtpPort(smtpPort);
                            email.setHostName(smtpServer);

                            email.send();
                        } catch (EmailException e) {
                            setError(messageNode, e.getMessage());
                            // Get the SMTP error code
                            // There has to be a better way to do this
                            if (e.getCause() != null && e.getCause().getMessage() != null) {
                                String smtpError = e.getCause().getMessage().trim();
                                try {
                                    int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                                    // All retry-able SMTP errors should have codes starting
                                    // with 4
                                    scheduleRetry(errorCode, messageNode);
                                } catch (NumberFormatException nfe) {
                                    // smtpError didn't start with an error code, let's dig for
                                    // it
                                    String searchFor = "response:";
                                    int rindex = smtpError.indexOf(searchFor);
                                    if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) {
                                        int errorCode = Integer.parseInt(smtpError.substring(searchFor.length(),
                                                searchFor.length() + 3));
                                        scheduleRetry(errorCode, messageNode);
                                    }
                                }
                            }
                        }
                    } else {
                        setError(messageNode, "Message must have a to and from set");
                    }
                } else {
                    setError(messageNode, "Not an outbox");
                }
                if (!messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                    messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT);
                }
            }
        } else {
            String retval = "null";
            if (objRcpt != null) {
                retval = objRcpt.getClass().toString();
            }
            setError(messageNode, "Expected recipients to be String or List<String>.  Found " + retval);
        }
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {/* w  w w . j  ava  2s  . com*/
        LOGGER.debug("Started handling email jms message.");

        String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
        String contentPath = message.getStringProperty(CONTENT_PATH_PROPERTY);
        Object objRcpt = message.getObjectProperty(RECIPIENTS);
        List<String> recipients = null;

        if (objRcpt instanceof List<?>) {
            recipients = (List<String>) objRcpt;
        } else if (objRcpt instanceof String) {
            recipients = new LinkedList<String>();
            String[] rcpts = StringUtils.split((String) objRcpt, ',');
            for (String rcpt : rcpts) {
                recipients.add(rcpt);
            }
        }

        if (contentPath != null && contentPath.length() > 0) {
            javax.jcr.Session adminSession = repository.loginAdministrative(null);
            org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils
                    .adaptToSession(adminSession);

            try {
                ContentManager contentManager = sparseSession.getContentManager();
                Content messageContent = contentManager.get(contentPath);

                if (objRcpt != null) {
                    // validate the message
                    if (messageContent != null) {
                        if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)
                                && (MessageConstants.BOX_OUTBOX.equals(
                                        messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX))
                                        || MessageConstants.BOX_PENDING.equals(messageContent
                                                .getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)))) {
                            if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                                // We're retrying this message, so clear the errors
                                messageContent.setProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR,
                                        (String) null);
                            }
                            if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_TO)
                                    && messageContent.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
                                // make a commons-email message from the message
                                MultiPartEmail email = null;
                                try {
                                    email = constructMessage(messageContent, recipients, adminSession,
                                            sparseSession);

                                    setOptions(email);
                                    if (LOGGER.isDebugEnabled()) {
                                        // build wrapped meesage in order to log it
                                        email.buildMimeMessage();
                                        logEmail(email);
                                    }
                                    email.send();
                                } catch (EmailException e) {
                                    String exMessage = e.getMessage();
                                    Throwable cause = e.getCause();

                                    setError(messageContent, exMessage);
                                    LOGGER.warn("Unable to send email: " + exMessage);

                                    // Get the SMTP error code
                                    // There has to be a better way to do this
                                    boolean rescheduled = false;
                                    if (cause != null && cause.getMessage() != null) {
                                        String smtpError = cause.getMessage().trim();
                                        try {
                                            int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                                            // All retry-able SMTP errors should have codes starting
                                            // with 4
                                            scheduleRetry(errorCode, messageContent);
                                            rescheduled = true;
                                        } catch (NumberFormatException nfe) {
                                            // smtpError didn't start with an error code, let's dig for
                                            // it
                                            String searchFor = "response:";
                                            int rindex = smtpError.indexOf(searchFor);
                                            if (rindex > -1
                                                    && (rindex + searchFor.length()) < smtpError.length()) {
                                                int errorCode = Integer.parseInt(smtpError
                                                        .substring(searchFor.length(), searchFor.length() + 3));
                                                scheduleRetry(errorCode, messageContent);
                                                rescheduled = true;
                                            } else if (!rescheduled
                                                    && cause.toString().contains("java.net.ConnectException")) {
                                                scheduleRetry(messageContent);
                                                rescheduled = true;
                                            }
                                        }
                                    }

                                    if (rescheduled) {
                                        LOGGER.info("Email {} rescheduled for redelivery. ", nodePath);
                                    } else {
                                        LOGGER.error(
                                                "Unable to reschedule email for delivery: " + e.getMessage(),
                                                e);
                                    }
                                }
                            } else {
                                setError(messageContent, "Message must have a to and from set");
                            }
                        } else {
                            setError(messageContent, "Not an outbox");
                        }
                        if (!messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                            messageContent.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX,
                                    MessageConstants.BOX_SENT);
                        }
                    }
                } else {
                    String retval = "null";
                    setError(messageContent,
                            "Expected recipients to be String or List<String>.  Found " + retval);
                }
            } finally {
                if (adminSession != null) {
                    adminSession.logout();
                }
            }
        }
    } catch (PathNotFoundException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (EmailDeliveryException e) {
        LOGGER.error(e.getMessage());
    } catch (ClientPoolException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (StorageClientException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//  w ww . j  a va  2  s.  c o  m
        LOGGER.debug("Started handling email jms message.");

        String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
        Object objRcpt = message.getObjectProperty(RECIPIENTS);
        List<String> recipients = null;

        if (objRcpt instanceof List<?>) {
            recipients = (List<String>) objRcpt;
        } else if (objRcpt instanceof String) {
            recipients = new LinkedList<String>();
            String[] rcpts = StringUtils.split((String) objRcpt, ',');
            for (String rcpt : rcpts) {
                recipients.add(rcpt);
            }
        }

        javax.jcr.Session adminSession = repository.loginAdministrative(null);
        Map<String, Object> authInfo = new HashMap<String, Object>();
        authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, adminSession);
        ResourceResolver resolver = resourceResolverFactory.getResourceResolver(authInfo);

        Node messageNode = resolver.getResource(nodePath).adaptTo(Node.class);

        if (objRcpt != null) {
            // validate the message
            if (messageNode != null) {
                if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)
                        && MessageConstants.BOX_OUTBOX.equals(
                                messageNode.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX).getString())) {
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                        // We're retrying this message, so clear the errors
                        messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null);
                    }
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_TO)
                            && messageNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
                        // make a commons-email message from the message
                        MultiPartEmail email = null;
                        try {
                            email = constructMessage(messageNode, recipients);

                            email.setSmtpPort(smtpPort);
                            email.setHostName(smtpServer);

                            email.send();
                        } catch (EmailException e) {
                            String exMessage = e.getMessage();
                            Throwable cause = e.getCause();

                            setError(messageNode, exMessage);
                            LOGGER.warn("Unable to send email: " + exMessage);

                            // Get the SMTP error code
                            // There has to be a better way to do this
                            boolean rescheduled = false;
                            if (cause != null && cause.getMessage() != null) {
                                String smtpError = cause.getMessage().trim();
                                try {
                                    int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                                    // All retry-able SMTP errors should have codes starting
                                    // with 4
                                    scheduleRetry(errorCode, messageNode);
                                    rescheduled = true;
                                } catch (NumberFormatException nfe) {
                                    // smtpError didn't start with an error code, let's dig for
                                    // it
                                    String searchFor = "response:";
                                    int rindex = smtpError.indexOf(searchFor);
                                    if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) {
                                        int errorCode = Integer.parseInt(smtpError.substring(searchFor.length(),
                                                searchFor.length() + 3));
                                        scheduleRetry(errorCode, messageNode);
                                        rescheduled = true;
                                    }
                                }
                            }
                            if (rescheduled) {
                                LOGGER.info("Email {} rescheduled for redelivery. ", nodePath);
                            } else {
                                LOGGER.error("Unable to reschedule email for delivery: " + e.getMessage(), e);
                            }
                        }
                    } else {
                        setError(messageNode, "Message must have a to and from set");
                    }
                } else {
                    setError(messageNode, "Not an outbox");
                }
                if (!messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                    messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT);
                }
            }
        } else {
            String retval = "null";
            setError(messageNode, "Expected recipients to be String or List<String>.  Found " + retval);
        }
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (LoginException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (EmailDeliveryException e) {
        LOGGER.error(e.getMessage());
    }
}

From source file:org.sonar.server.notification.email.EmailNotificationChannelTest.java

@Test
public void shouldSendTestEmailWithSTARTTLS() {
    smtpServer.getServer().setEnableTLS(true);
    smtpServer.getServer().setRequireTLS(true);
    configure();//from   www.  j av a2  s  .  co  m
    when(configuration.getSecureConnection()).thenReturn("STARTTLS");

    try {
        underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube",
                "This is a test message from SonarQube.");
        fail("An SSL exception was expected a a proof that STARTTLS is enabled");
    } catch (EmailException e) {
        // We don't have a SSL certificate so we are expecting a SSL error
        assertThat(e.getCause().getMessage()).isEqualTo("Could not convert socket to TLS");
    }
}