Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:voldemort.restclient.R2Store.java

private List<Versioned<byte[]>> parseGetResponse(ByteString entity) {
    List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>();

    try {//w w w  . ja v a2  s .c o m
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);
            String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
            int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

            if (logger.isDebugEnabled()) {
                logger.debug("Received VC : " + serializedVC);
            }
            VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

            InputStream input = part.getInputStream();
            byte[] bodyPartBytes = new byte[contentLength];
            input.read(bodyPartBytes);

            VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
            results.add(new Versioned<byte[]>(bodyPartBytes, clock));

        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

public void sendMessage(GWTMessage message) throws Exception {

    try {/* ww  w. j a va 2 s  .  c  o m*/
        log.debug("sending message...");
        MessageHandler messageHandler = SessionManager.get().getCurrentComposeMessage();
        messageHandler.setGWTMessage(message);
        messageHandler.send();
        IMailbox mailbox = SessionManager.get().getMailbox();
        IMailFolder sentFolder = mailbox.getSentFolder();
        messageHandler.saveToFolder(sentFolder, false);
        log.debug("...successful");

        try {
            getUserAccountDao().saveRecipients(SessionManager.get().getUserAccount(),
                    messageHandler.getAllRecipients());
        } catch (Throwable e) {
            // catch all exceptions
            log.error(e.getMessage(), e);
        }
    } catch (AddressException e) {
        log.error(e.getMessage(), e);
        throw new GWTInvalidAddressException(e.getMessage(), e.getRef());
    } catch (SendFailedException e) {
        log.error(e.getMessage(), e);
        if ("Invalid Addresses".equals(e.getMessage())) {
            String address = "";
            try {
                address = MessageUtils.getMailAdressString(e.getInvalidAddresses(), AddressStringType.PERSONAL);
            } catch (MessagingException ex) {
                log.error(ex.getMessage(), ex);
            }
            throw new GWTInvalidAddressException(e.getMessage(), address);
        } else {
            throw new GWTMessageException(e.getMessage());
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    }
}

From source file:voldemort.restclient.R2Store.java

private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) {
    Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>();

    try {/*from  w w  w  .j  av a 2  s  .c  o  m*/
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        // Get the outer multipart object
        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {

            // Get an individual part. This contains all the versioned
            // values for a particular key referenced by content-location
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);

            // Get the key
            String contentLocation = part.getHeader("Content-Location")[0];
            String base64Key = contentLocation.split("/")[2];
            ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key));

            if (logger.isDebugEnabled()) {
                logger.debug("Content-Location : " + contentLocation);
                logger.debug("Base 64 key : " + base64Key);
            }

            // Create an array list for holding all the (versioned values)
            List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>();

            // Get the nested Multi-part object. This contains one part for
            // each unique versioned value.
            ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(),
                    "multipart/mixed");
            MimeMultipart valueParts = new MimeMultipart(nestedDS);

            for (int valueId = 0; valueId < valueParts.getCount(); valueId++) {

                MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId);
                String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
                int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

                if (logger.isDebugEnabled()) {
                    logger.debug("Received serialized Vector Clock : " + serializedVC);
                }

                VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

                // get the value bytes
                InputStream input = valuePart.getInputStream();
                byte[] bodyPartBytes = new byte[contentLength];
                input.read(bodyPartBytes);

                VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
                valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock));

            }
            results.put(key, valueResultList);
        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:org.nuxeo.ecm.platform.ec.notification.NotificationEventListener.java

public void sendNotification(Event event, DocumentEventContext ctx) {

    String eventId = event.getName();
    log.debug("Received a message for notification sender with eventId : " + eventId);

    Map<String, Serializable> eventInfo = ctx.getProperties();
    String userDest = (String) eventInfo.get(NotificationConstants.DESTINATION_KEY);
    NotificationImpl notif = (NotificationImpl) eventInfo.get(NotificationConstants.NOTIFICATION_KEY);

    // send email
    NuxeoPrincipal recepient = NotificationServiceHelper.getUsersService().getPrincipal(userDest);
    if (recepient == null) {
        log.error("Couldn't find user: " + userDest + " to send her a mail.");
        return;//  ww  w. j av  a  2 s. c  o m
    }
    String email = recepient.getEmail();
    if (email == null || "".equals(email)) {
        log.error("No email found for user: " + userDest);
        return;
    }

    String subjectTemplate = notif.getSubjectTemplate();

    String mailTemplate = null;
    // mail template can be dynamically computed from a MVEL expression
    if (notif.getTemplateExpr() != null) {
        try {
            mailTemplate = emailHelper.evaluateMvelExpresssion(notif.getTemplateExpr(), eventInfo);
        } catch (PropertyAccessException pae) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot evaluate mail template expression '" + notif.getTemplateExpr()
                        + "' in that context " + eventInfo, pae);
            }
        }
    }
    // if there is no mailTemplate evaluated, use the defined one
    if (StringUtils.isEmpty(mailTemplate)) {
        mailTemplate = notif.getTemplate();
    }

    log.debug("email: " + email);
    log.debug("mail template: " + mailTemplate);
    log.debug("subject template: " + subjectTemplate);

    Map<String, Object> mail = new HashMap<String, Object>();
    mail.put("mail.to", email);

    String authorUsername = (String) eventInfo.get(NotificationConstants.AUTHOR_KEY);

    if (authorUsername != null) {
        NuxeoPrincipal author = NotificationServiceHelper.getUsersService().getPrincipal(authorUsername);
        mail.put(NotificationConstants.PRINCIPAL_AUTHOR_KEY, author);
    }

    mail.put(NotificationConstants.DOCUMENT_KEY, ctx.getSourceDocument());
    String subject = notif.getSubject() == null ? NotificationConstants.NOTIFICATION_KEY : notif.getSubject();
    subject = notificationService.getEMailSubjectPrefix() + subject;
    mail.put("subject", subject);
    mail.put("template", mailTemplate);
    mail.put("subjectTemplate", subjectTemplate);

    // Transferring all data from event to email
    for (String key : eventInfo.keySet()) {
        mail.put(key, eventInfo.get(key) == null ? "" : eventInfo.get(key));
        log.debug("Mail prop: " + key);
    }

    mail.put(NotificationConstants.EVENT_ID_KEY, eventId);

    try {
        emailHelper.sendmail(mail);
    } catch (MessagingException e) {
        String cause = "";
        if ((e instanceof SendFailedException) && (e.getCause() instanceof SendFailedException)) {
            cause = " - Cause: " + e.getCause().getMessage();
        }
        log.warn("Failed to send notification email to '" + email + "': " + e.getClass().getName() + ": "
                + e.getMessage() + cause);
    }
}

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

/**
 * Build error message from the exception.
 *//*ww w. ja va 2  s. c o  m*/
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:com.cubusmail.gwtui.server.services.MailboxService.java

public GWTMessageList retrieveMessages(String folderId, int start, int pageSize, String sortField, String dir,
        String[][] params) throws Exception {

    if (folderId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        UserAccount account = SessionManager.get().getUserAccount();
        log.debug("retrieving messages from " + folderId + " ...");

        try {//from   w  ww.  j  a v a2s. c  o m
            IMailFolder currentFolder = mailbox.getMailFolderById(folderId);
            mailbox.setCurrentFolder(currentFolder);

            Message[] msgs = currentFolder.retrieveMessages(sortField);

            String quickSearchFields = MessageUtils.getParamValue(params, "fields");
            String extendedSearchFields = MessageUtils.getParamValue(params,
                    GWTMailConstants.EXTENDED_SEARCH_FIELDS);

            // all messages with only header data

            // quick search params
            if (quickSearchFields != null) {
                String quickSearchText = MessageUtils.getParamValue(params, "query");
                msgs = MessageUtils.quickFilterMessages(msgs, quickSearchFields, quickSearchText);
            } else if (extendedSearchFields != null) {
                msgs = MessageUtils.filterMessages(currentFolder, msgs, extendedSearchFields, params);
            }

            boolean ascending = "ASC".equals(dir);
            MessageUtils.sortMessages(msgs, sortField, ascending);

            if (msgs != null && msgs.length > 0) {
                log.debug("Building Array objects...");
                long time = System.currentTimeMillis();

                int total_count = msgs.length;
                start = Math.min(total_count - 1, start == -1 ? 0 : start);
                pageSize = pageSize == -1 ? account.getPreferences().getPageCount() : pageSize;
                pageSize = Math.min(pageSize, total_count - start);

                Message[] pagedMessages = new Message[pageSize];
                int pagedIndex = 0;
                for (int msgIndex = start; msgIndex < start + pageSize; msgIndex++) {
                    pagedMessages[pagedIndex++] = msgs[msgIndex];
                }
                FetchProfile completeProfile = MessageUtils.createFetchProfile(true, null);
                currentFolder.fetch(pagedMessages, completeProfile);

                String[][] messageStringArray = new String[pageSize][MessageListFields.values().length];
                Preferences preferences = SessionManager.get().getPreferences();

                // get date formats for message list date
                Locale locale = SessionManager.get().getLocale();
                TimeZone timezone = SessionManager.get().getTimeZone();
                String datePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_DATE_FORMAT_PATTERN, null, locale);
                String timePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_TIME_FORMAT_PATTERN, null, locale);

                NumberFormat sizeFormat = MessageUtils.createSizeFormat(locale);

                DateFormat dateFormat = null;
                DateFormat timeFormat = null;
                if (preferences.isShortTimeFormat()) {
                    dateFormat = new SimpleDateFormat(datePattern, locale);
                    timeFormat = new SimpleDateFormat(timePattern, locale);
                    timeFormat.setTimeZone(timezone);
                } else {
                    dateFormat = new SimpleDateFormat(datePattern + " " + timePattern, locale);
                }
                dateFormat.setTimeZone(timezone);
                Date today = Calendar.getInstance(timezone).getTime();

                for (int i = 0; i < pageSize; i++) {
                    if (preferences.isShortTimeFormat()
                            && DateUtils.isSameDay(today, pagedMessages[i].getSentDate())) {
                        // show only time
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                timeFormat, sizeFormat);
                    } else {
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                dateFormat, sizeFormat);
                    }
                }
                log.debug("..finish. Time for building Array: " + (System.currentTimeMillis() - time));

                return new GWTMessageList(messageStringArray, msgs.length);
            }

            return null;
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            throw new GWTMessageException(e.getMessage());
        }
    } else {
        return null;
    }
}

From source file:com.krawler.esp.handlers.zohoRequestHandler.java

@Override
public void run() {
    //        new TransactionTemplate(transactionManager)
    //               .execute(new TransactionCallbackWithoutResult() {
    //                  @Override
    //                  public void doInTransactionWithoutResult(TransactionStatus status) {
    //                     dao.lock(client, NONE);
    //                     dao.save(new Report(client, client.getTotal()));
    //                     client.setLastCreated(new Date());
    //                  }
    //               });

    //        Session session = null;
    try {/*from  w ww.jav a2 s  .  c  om*/
        while (!processQueue.isEmpty()) {
            JSONObject tempObj = (JSONObject) processQueue.get(0);
            try {
                this.isWorking = true;

                String username = tempObj.getString("username");
                String password = tempObj.getString("password");
                //String apiKey  = tempObj.getString("apikey");
                String authToken = tempObj.getString("authtoken");
                String userid = tempObj.getString("userid");
                String companyid = tempObj.getString("companyid");
                String ipAddress = tempObj.getString("ipaddress");
                String tzDiff = tempObj.getString("tzdiff");
                String parterName = tempObj.getString(Constants.SESSION_PARTNERNAME);
                String sysEmailId = tempObj.getString("sysemailid");
                JSONObject accountResult = null;
                JSONObject leadResult = null;
                JSONObject potentialResult = null;
                JSONObject contactResult = null;
                String result = "";
                if (tempObj.getBoolean("accounts")) {
                    result = saveUpdateZohoAccounts(username, password, authToken, userid, companyid);
                    accountResult = new JSONObject(result);
                }
                if (tempObj.getBoolean("leads")) {
                    result = saveUpdateZohoLeads(username, password, authToken, userid, companyid);
                    leadResult = new JSONObject(result);
                }
                if (tempObj.getBoolean("potentials")) {
                    result = saveUpdateZohoPotentials(username, password, authToken, userid, companyid);
                    potentialResult = new JSONObject(result);
                }
                if (tempObj.getBoolean("contacts")) {
                    result = saveUpdateZohoContact(username, password, authToken, userid, companyid, ipAddress,
                            tzDiff);
                    contactResult = new JSONObject(result);
                }

                String htmltxt = "Report for data imported from zoho.<br/>";
                String plainMsg = "Report for data imported from zoho.\n";

                zohoImportLog zlog = new zohoImportLog();
                if (accountResult != null) {

                    zlog.setAccounts(Integer.parseInt(accountResult.getString("recCount")));
                    zlog.setFailedAccounts(
                            (accountResult.getInt("totalRecords") - accountResult.getInt("recCount")));
                    htmltxt += "<br/><br/>Accounts:<br/>";
                    htmltxt += "Total Records Imported: " + accountResult.getString("recCount");
                    htmltxt += "<br/>Failed Records: "
                            + (accountResult.getInt("totalRecords") - accountResult.getInt("recCount"));
                    plainMsg += "\nAccounts:\n";
                    plainMsg += "Total Records Imported: " + accountResult.getString("recCount");
                    plainMsg += "\nFailed Records: "
                            + (accountResult.getInt("totalRecords") - accountResult.getInt("recCount"));
                }
                if (leadResult != null) {
                    zlog.setLeads(Integer.parseInt(leadResult.getString("recCount")));
                    zlog.setFailedLeads((leadResult.getInt("totalRecords") - leadResult.getInt("recCount")));
                    htmltxt += "<br/><br/>Leads:<br/>";
                    htmltxt += "Total Records Imported: " + leadResult.getString("recCount");
                    htmltxt += "<br/>Failed Records: "
                            + (leadResult.getInt("totalRecords") - leadResult.getInt("recCount"));
                    plainMsg += "\nLeads:\n";
                    plainMsg += "Total Records Imported: " + leadResult.getString("recCount");
                    plainMsg += "\nFailed Records: "
                            + (leadResult.getInt("totalRecords") - leadResult.getInt("recCount"));
                }
                if (potentialResult != null) {
                    zlog.setPotentials(Integer.parseInt(potentialResult.getString("recCount")));
                    zlog.setFailedPotentials(
                            (potentialResult.getInt("totalRecords") - potentialResult.getInt("recCount")));
                    htmltxt += "<br/><br/>Potentials:<br/>";
                    htmltxt += "Total Records Imported: " + potentialResult.getString("recCount");
                    htmltxt += "<br/>Failed Records: "
                            + (potentialResult.getInt("totalRecords") - potentialResult.getInt("recCount"));
                    plainMsg += "\nPotentials:\n";
                    plainMsg += "Total Records Imported: " + potentialResult.getString("recCount");
                    plainMsg += "\nFailed Records: "
                            + (potentialResult.getInt("totalRecords") - potentialResult.getInt("recCount"));
                }
                if (contactResult != null) {
                    zlog.setContacts(Integer.parseInt(contactResult.getString("recCount")));
                    zlog.setFailedContacts(
                            (contactResult.getInt("totalRecords") - contactResult.getInt("recCount")));
                    htmltxt += "<br/><br/>Contacts:<br/>";
                    htmltxt += "Total Records Imported: " + contactResult.getString("recCount");
                    htmltxt += "<br/>Failed Records: "
                            + (contactResult.getInt("totalRecords") - contactResult.getInt("recCount"));
                    plainMsg += "\nContacts:\n";
                    plainMsg += "Total Records Imported: " + contactResult.getString("recCount");
                    plainMsg += "\nFailed Records: "
                            + (contactResult.getInt("totalRecords") - contactResult.getInt("recCount"));
                }
                htmltxt += "<br/><br/>For queries, email us at support@deskera.com<br/>";
                htmltxt += parterName + " Team";
                plainMsg += "\nFor queries, email us at support@deskera.com\n";
                plainMsg += parterName + " Team";

                //                session = zohoRequestDAO.getCurrentSession();
                //                Transaction tx = session.beginTransaction();
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setName("JE_Tx");
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
                TransactionStatus status = txnManager.getTransaction(def);
                User u = (User) zohoRequestDAO.get(User.class, userid);

                zlog.setUserid(userid);
                zlog.setCompanyid(companyid);
                zlog.setDate(new java.util.Date());
                zlog.setZusername(username);
                zohoRequestDAO.save(zlog);
                txnManager.commit(status);
                //                tx.commit();
                SendMailHandler.postMail(new String[] { u.getEmailID() },
                        parterName + " CRM - Report for data imported from zoho", htmltxt, plainMsg,
                        parterName + " Admin<" + sysEmailId + ">");

            } catch (MessagingException ex) {
                logger.warn(ex.getMessage(), ex);
            } catch (JSONException ex) {
                logger.warn(ex.getMessage(), ex);
            } finally {
                //                session.close();
                processQueue.remove(tempObj);
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    } finally {
        this.isWorking = false;
    }
}

From source file:com.cws.us.pws.controllers.CommonController.java

@RequestMapping(value = "/contact", method = RequestMethod.POST)
public final ModelAndView sendMessage(@ModelAttribute("message") final EmailMessage message,
        final BindingResult bindResult) {
    final String methodName = CommonController.CNAME
            + "#sendMessage(@ModelAttribute(\"message\") final EmailMessage message, final BindingResult bindResult)";

    if (DEBUG) {/*from   w w  w. j a  v a 2s  .c  o  m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("EmailMessage: {}", message);
        DEBUGGER.debug("BindingResult: {}", bindResult);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("Session ID: {}", hSession.getId());

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    // validate
    this.appConfig.getEmailValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    this.appConfig.getMessageValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView = new ModelAndView();
        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    try {
        EmailUtils.sendEmailMessage(message, true);

        EmailMessage autoResponse = new EmailMessage();
        autoResponse.setIsAlert(false);
        autoResponse.setMessageSubject(this.contactResponseEmail.getSubject());
        autoResponse.setMessageTo(new ArrayList<>(Arrays
                .asList(String.format(this.contactResponseEmail.getTo()[0], message.getEmailAddr().get(0)))));
        autoResponse.setEmailAddr(
                new ArrayList<>(Arrays.asList(String.format(this.contactResponseEmail.getFrom()))));
        autoResponse.setMessageBody(String.format(this.contactResponseEmail.getText(), message.getEmailAddr(),
                message.getMessageBody()));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", autoResponse);
        }

        EmailUtils.sendEmailMessage(autoResponse, true);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getRequestCompletePage());
    } catch (MessagingException msx) {
        ERROR_RECORDER.error(msx.getMessage(), msx);

        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

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.
 * // ww w  .ja  v a  2s .  c om
 * @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.cubusmail.server.mail.MessageHandler.java

/**
 * @param session//from w  w  w  .  jav a 2s. co m
 * @param message
 */
public void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}