Example usage for org.springframework.mail MailPreparationException MailPreparationException

List of usage examples for org.springframework.mail MailPreparationException MailPreparationException

Introduction

In this page you can find the example usage for org.springframework.mail MailPreparationException MailPreparationException.

Prototype

public MailPreparationException(Throwable cause) 

Source Link

Usage

From source file:org.smigo.config.DevelopmentConfiguration.java

@Bean
public JavaMailSenderImpl javaMailSender() {
    return new JavaMailSenderImpl() {
        @Override// w w w.j a v  a2s .c o m
        public String getDefaultEncoding() {
            return "UTF-8";
        }

        @Override
        public void send(SimpleMailMessage simpleMessage) throws MailException {
            try {
                //Thread.sleep(2000);
                String text = simpleMessage.getText();
                String subject = simpleMessage.getSubject();
                FileUtils.writeStringToFile(MAIL_FILE, text, Charset.defaultCharset());
                FileUtils.writeStringToFile(MAIL_FILE_TXT, subject + System.lineSeparator() + text,
                        Charset.defaultCharset());
            } catch (Exception e) {
                throw new MailSendException("Error sending email to " + simpleMessage.getFrom(), e);
            }
        }

        @Override
        public void send(MimeMessage mimeMessage) throws MailException {
            try {
                final String s = IOUtils.toString(mimeMessage.getInputStream());
                FileUtils.writeStringToFile(MAIL_FILE, s, Charset.defaultCharset());
            } catch (IOException | MessagingException e) {
                throw new MailSendException("Error sending email: " + mimeMessage.toString(), e);
            }
        }

        @Override
        public void send(SimpleMailMessage[] simpleMessages) throws MailException {
            throw new MailPreparationException("Method not supported");
        }
    };
}

From source file:net.malariagen.alfresco.action.CustomMailAction.java

public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef,
        final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) {
    // Create the mime mail message.
    // Hack: using an array here to get around the fact that inner classes
    // aren't closures.
    // The MimeMessagePreparator.prepare() signature does not allow us to
    // return a value and yet
    // we can't set a result on a bare, non-final object reference due to
    // Java language restrictions.
    final MimeMessageHelper[] messageRef = new MimeMessageHelper[1];
    MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
        @SuppressWarnings("unchecked")
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            if (logger.isDebugEnabled()) {
                logger.debug(ruleAction.getParameterValues());
            }//from  ww w . j av a2  s .c o  m

            messageRef[0] = new MimeMessageHelper(mimeMessage);

            // set header encoding if one has been supplied
            if (headerEncoding != null && headerEncoding.length() != 0) {
                mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding);
            }

            String listHeaders = (String) ruleAction.getParameterValue(PARAM_LIST_ID);
            if (listHeaders != null) {
                mimeMessage.setHeader("List-Id",
                        "<" + listHeaders + "." + sysAdminParams.getAlfrescoHost() + ">");
                mimeMessage.setHeader("X-Auto-Response-Suppress", "All");
                mimeMessage.setHeader("Precedence", "list");
                mimeMessage.setHeader("auto-submitted", "auto-generated");
            }

            // set recipient
            // I don't think this is used - see getRecipients in parent
            String to = (String) ruleAction.getParameterValue(PARAM_TO);
            if (to != null && to.length() != 0) {
                messageRef[0].setTo(to);

                // Note: there is no validation on the username to check
                // that it actually is an email address.
                // TODO Fix this.

                Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC);
                if (ccValue != null) {
                    if (ccValue instanceof String) {
                        String cc = (String) ccValue;
                        if (cc.length() > 0) {
                            messageRef[0].setCc(cc);
                        }

                    } else if (ccValue instanceof List<?>) {
                        List<String> s = (List<String>) ccValue;
                        messageRef[0].setCc((String[]) s.toArray());
                    } else if (ccValue.getClass().isArray()) {
                        messageRef[0].setCc((String[]) ccValue);
                    }

                }
                Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC);
                if (bccValue != null) {
                    if (bccValue instanceof String) {
                        String bcc = (String) bccValue;
                        if (bcc.length() > 0) {
                            messageRef[0].setBcc(bcc);
                        }

                    } else if (bccValue instanceof List<?>) {
                        List<String> s = (List<String>) bccValue;
                        messageRef[0].setBcc((String[]) s.toArray());
                    } else if (bccValue.getClass().isArray()) {
                        messageRef[0].setCc((String[]) bccValue);
                    }
                }

            } else {
                // see if multiple recipients have been supplied - as a list
                // of authorities
                Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY);
                List<String> authorities = null;
                if (authoritiesValue != null) {
                    if (authoritiesValue instanceof String) {
                        authorities = new ArrayList<String>(1);
                        authorities.add((String) authoritiesValue);
                    } else {
                        authorities = (List<String>) authoritiesValue;
                    }
                }

                if (authorities != null && authorities.size() != 0) {
                    List<String> recipients = new ArrayList<String>(authorities.size());

                    if (logger.isTraceEnabled()) {
                        logger.trace(authorities.size() + " recipient(s) for mail");
                    }

                    for (String authority : authorities) {
                        final AuthorityType authType = AuthorityType.getAuthorityType(authority);

                        if (logger.isTraceEnabled()) {
                            logger.trace(" authority type: " + authType);
                        }

                        if (authType.equals(AuthorityType.USER)) {
                            if (personService.personExists(authority) == true) {
                                NodeRef person = personService.getPerson(authority);

                                if (!personService.isEnabled(authority)
                                        && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) {
                                    continue;
                                }

                                String address = (String) nodeService.getProperty(person,
                                        ContentModel.PROP_EMAIL);
                                if (address != null && address.length() != 0 && validateAddress(address)) {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace("Recipient (person) exists in Alfresco with known email.");
                                    }
                                    recipients.add(address);
                                } else {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace(
                                                "Recipient (person) exists in Alfresco without known email.");
                                    }
                                    // If the username looks like an email
                                    // address, we'll use that.
                                    if (validateAddress(authority)) {
                                        recipients.add(authority);
                                    }
                                }
                            } else {
                                if (logger.isTraceEnabled()) {
                                    logger.trace("Recipient does not exist in Alfresco.");
                                }
                                if (validateAddress(authority)) {
                                    recipients.add(authority);
                                }
                            }
                        } else if (authType.equals(AuthorityType.GROUP)
                                || authType.equals(AuthorityType.EVERYONE)) {
                            if (logger.isTraceEnabled()) {
                                logger.trace("Recipient is a group...");
                            }
                            // Notify all members of the group
                            Set<String> users;
                            if (authType.equals(AuthorityType.GROUP)) {
                                users = authorityService.getContainedAuthorities(AuthorityType.USER, authority,
                                        false);
                            } else {
                                users = authorityService.getAllAuthorities(AuthorityType.USER);
                            }

                            for (String userAuth : users) {
                                if (personService.personExists(userAuth) == true) {
                                    NodeRef person = personService.getPerson(userAuth);

                                    String address = (String) nodeService.getProperty(person,
                                            ContentModel.PROP_EMAIL);
                                    if (address != null && address.length() != 0) {
                                        recipients.add(address);
                                        if (logger.isTraceEnabled()) {
                                            logger.trace("   Group member email is known.");
                                        }
                                    } else {
                                        if (logger.isTraceEnabled()) {
                                            logger.trace("   Group member email not known.");
                                        }
                                        if (validateAddress(authority)) {
                                            recipients.add(userAuth);
                                        }
                                    }
                                } else {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace("   Group member person not found");
                                    }
                                    if (validateAddress(authority)) {
                                        recipients.add(userAuth);
                                    }
                                }
                            }
                        }
                    }

                    if (logger.isTraceEnabled()) {
                        logger.trace(recipients.size() + " valid recipient(s).");
                    }

                    if (recipients.size() > 0) {
                        messageRef[0].setTo(recipients.toArray(new String[recipients.size()]));
                    } else {
                        // All recipients were invalid
                        throw new MailPreparationException("All recipients for the mail action were invalid");
                    }
                } else {
                    // No recipients have been specified
                    throw new MailPreparationException("No recipient has been specified for the mail action");
                }
            }

            // from person - not to be performed for the "admin" or "system"
            // users
            NodeRef fromPerson = null;

            final String currentUserName = authService.getCurrentUserName();

            final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] {
                    AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() });
            if (!usersNotToBeUsedInFromField.contains(currentUserName)) {
                fromPerson = personService.getPerson(currentUserName);
            }

            if (isFromEnabled()) {
                // Use the FROM parameter in preference to calculating
                // values.
                String from = (String) ruleAction.getParameterValue(PARAM_FROM);
                if (from != null && from.length() > 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("from specified as a parameter, from:" + from);
                    }

                    // Check whether or not to use a personal name for the
                    // email (will be RFC 2047 encoded)
                    String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME);
                    if (fromPersonalName != null && fromPersonalName.length() > 0) {
                        try {
                            messageRef[0].setFrom(from, fromPersonalName);
                        } catch (UnsupportedEncodingException error) {
                            // Uses the JVM's default encoding, can never be
                            // unsupported. Just in case, revert to simple
                            // email
                            messageRef[0].setFrom(from);
                        }
                    } else {
                        messageRef[0].setFrom(from);
                    }
                    setReplyTo(ruleAction, messageRef, from);
                } else {
                    // set the from address from the current user
                    String fromActualUser = null;
                    if (fromPerson != null) {
                        fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL);
                    }

                    if (fromActualUser != null && fromActualUser.length() != 0) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("looked up email address for :" + fromPerson + " email from "
                                    + fromActualUser);
                        }
                        messageRef[0].setFrom(fromActualUser);
                        setReplyTo(ruleAction, messageRef, fromDefaultAddress);
                    } else {
                        // from system or user does not have email address
                        messageRef[0].setFrom(fromDefaultAddress);
                        setReplyTo(ruleAction, messageRef, fromDefaultAddress);
                    }
                }

            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("from not enabled - sending from default address:" + fromDefaultAddress);
                }
                // from is not enabled.
                messageRef[0].setFrom(fromDefaultAddress);
                setReplyTo(ruleAction, messageRef, fromDefaultAddress);
            }

            // set subject line
            messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

            if ((testModeRecipient != null) && (testModeRecipient.length() > 0)
                    && (!testModeRecipient.equals("${dev.email.recipient.address}"))) {
                // If we have an override for the email recipient, we'll
                // send the email to that address instead.
                // We'll prefix the subject with the original recipient, but
                // leave the email message unchanged in every other way.
                messageRef[0].setTo(testModeRecipient);

                String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO);
                if (emailRecipient == null) {
                    Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
                    if (obj != null) {
                        emailRecipient = obj.toString();
                    }
                }

                String recipientPrefixedSubject = "(" + emailRecipient + ") "
                        + (String) ruleAction.getParameterValue(PARAM_SUBJECT);

                messageRef[0].setSubject(recipientPrefixedSubject);
            }

            // See if an email template has been specified
            String text = null;

            // templateRef: either a nodeRef or classpath (see
            // ClasspathRepoTemplateLoader)
            Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE);
            String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref);
            if (templateRef != null) {
                Map<String, Object> suppliedModel = null;
                if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) {
                    Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL);
                    if (m instanceof Map) {
                        suppliedModel = (Map<String, Object>) m;
                    } else {
                        logger.warn("Skipping unsupported email template model parameters of type "
                                + m.getClass().getName() + " : " + m.toString());
                    }
                }

                // build the email template model
                Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel,
                        fromPerson);

                // Determine the locale to use to send the email.
                Locale locale = recipient.getSecond();
                if (locale == null) {
                    locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE);
                }
                if (locale == null) {
                    locale = sender.getSecond();
                }

                // set subject line
                String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT);
                Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS);
                Object[] subjectParams = null;
                // Javasctipt pass SubjectParams as ArrayList. see MNT-12534
                if (subjectParamsObject instanceof List) {
                    subjectParams = ((List<Object>) subjectParamsObject).toArray();
                } else if (subjectParamsObject instanceof Object[]) {
                    subjectParams = (Object[]) subjectParamsObject;
                } else {
                    if (subjectParamsObject != null) {
                        subjectParams = new Object[] { subjectParamsObject.toString() };
                    }
                }
                String localizedSubject = getLocalizedSubject(subject, subjectParams, locale);
                if (locale == null) {
                    // process the template against the model
                    text = templateService.processTemplate("freemarker", templateRef, model);
                } else {
                    // process the template against the model
                    text = templateService.processTemplate("freemarker", templateRef, model, locale);
                }
                if ((testModeRecipient != null) && (testModeRecipient.length() > 0)
                        && (!testModeRecipient.equals("${dev.email.recipient.address}"))) {
                    // If we have an override for the email recipient, we'll
                    // send the email to that address instead.
                    // We'll prefix the subject with the original recipient,
                    // but leave the email message unchanged in every other
                    // way.
                    messageRef[0].setTo(testModeRecipient);

                    String emailRecipient = recipient.getFirst();

                    String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject;

                    messageRef[0].setSubject(recipientPrefixedSubject);
                } else {
                    messageRef[0].setTo(recipient.getFirst());
                    messageRef[0].setSubject(localizedSubject);
                }
            }

            // set the text body of the message

            boolean isHTML = false;
            if (text == null) {
                text = (String) ruleAction.getParameterValue(PARAM_TEXT);
            }

            if (text != null) {
                if (isHTML(text)) {
                    isHTML = true;
                }
            } else {
                text = (String) ruleAction.getParameterValue(PARAM_HTML);
                if (text != null) {
                    // assume HTML
                    isHTML = true;
                }
            }

            if (text != null) {
                messageRef[0].setText(text, isHTML);
            }

        }

        private void setReplyTo(final Action ruleAction, final MimeMessageHelper[] messageRef, String from)
                throws MessagingException {
            // ResponseNode can be a Long as well as Text
            Object responseNode = ruleAction.getParameterValue(PARAM_RESPONSE_NODE);

            if (responseNode != null) {
                // Assuming address is valid...
                String[] parts = from.split("@");
                messageRef[0].setReplyTo(parts[0] + "+" + responseNode + "@" + parts[1]);
            }
        }
    };
    MimeMessage mimeMessage = mailService.createMimeMessage();
    try {
        mailPreparer.prepare(mimeMessage);
    } catch (Exception e) {
        // We're forced to catch java.lang.Exception here. Urgh.
        if (logger.isWarnEnabled()) {
            logger.warn("Unable to prepare mail message. Skipping.", e);
        }
        return null;
    }

    return messageRef[0];
}

From source file:net.malariagen.alfresco.action.CustomMailAction.java

@SuppressWarnings("unchecked")
private Collection<Pair<String, Locale>> getRecipients(Action ruleAction) {
    Map<String, Pair<String, Locale>> recipients = new HashMap<String, Pair<String, Locale>>();

    // set recipient
    String to = (String) ruleAction.getParameterValue(PARAM_TO);
    if (to != null && to.length() != 0) {
        Locale locale = null;/*from  w ww .ja v a2s  .c  o  m*/
        if (personExists(to)) {
            locale = getLocaleForUser(to);
        }
        recipients.put(to, new Pair<String, Locale>(to, locale));
    } else {
        // see if multiple recipients have been supplied - as a list of
        // authorities
        Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY);
        List<String> authorities = null;
        if (authoritiesValue != null) {
            if (authoritiesValue instanceof String) {
                authorities = new ArrayList<String>(1);
                authorities.add((String) authoritiesValue);
            } else {
                authorities = (List<String>) authoritiesValue;
            }
        }

        if (authorities != null && authorities.size() != 0) {
            for (String authority : authorities) {
                AuthorityType authType = AuthorityType.getAuthorityType(authority);
                if (authType.equals(AuthorityType.USER)) {
                    // Formerly, this code checked personExists(auth) but we
                    // now support emailing addresses who are not yet
                    // Alfresco users.
                    // Check the user name to be a valid email and we don't
                    // need to log an error in this case
                    // ALF-19231
                    // Validate the email, allowing for local email
                    // addresses
                    if ((authority != null) && (authority.length() != 0)
                            && (!recipients.containsKey(authority))) {
                        if (personExists(authority)) {
                            if (isControlledActivity(ruleAction, authority)) {
                                continue;
                            }
                            String address = getPersonEmail(authority);
                            if (address != null && address.length() != 0 && validateAddress(address)) {
                                Locale locale = getLocaleForUser(authority);
                                recipients.put(authority, new Pair<String, Locale>(address, locale));
                            } else {
                                EmailValidator emailValidator = EmailValidator.getInstance(true);
                                if (validateAddresses && emailValidator.isValid(authority)) {
                                    Locale locale = getLocaleForUser(authority);
                                    recipients.put(authority, new Pair<String, Locale>(authority, locale));
                                }
                            }
                        } else {
                            recipients.put(authority, new Pair<String, Locale>(authority, null));
                        }
                    }
                } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) {
                    // Notify all members of the group
                    Set<String> users;
                    if (authType.equals(AuthorityType.GROUP)) {
                        users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false);
                    } else {
                        users = authorityService.getAllAuthorities(AuthorityType.USER);
                    }

                    for (String userAuth : users) {
                        if (recipients.containsKey(userAuth)) {
                            continue;
                        }
                        if (personExists(userAuth)) {
                            if (isControlledActivity(ruleAction, userAuth)) {
                                continue;
                            }
                            // Check the user name to be a valid email and
                            // we don't need to log an error in this case
                            // ALF-19231
                            // Validate the email, allowing for local email
                            // addresses
                            String address = getPersonEmail(userAuth);
                            if (address != null && address.length() != 0 && validateAddress(address)) {
                                Locale locale = getLocaleForUser(userAuth);
                                recipients.put(userAuth, new Pair<String, Locale>(address, locale));
                            } else {
                                EmailValidator emailValidator = EmailValidator.getInstance(true);
                                if (validateAddresses && emailValidator.isValid(userAuth)) {
                                    if (userAuth != null && userAuth.length() != 0) {
                                        Locale locale = getLocaleForUser(userAuth);
                                        recipients.put(userAuth, new Pair<String, Locale>(userAuth, locale));
                                    }
                                }
                            }
                        } else {
                            recipients.put(userAuth, new Pair<String, Locale>(authority, null));
                        }
                    }
                }
            }
            if (recipients.size() <= 0) {
                // All recipients were invalid
                throw new MailPreparationException("All recipients for the mail action were invalid");
            }
        } else {
            // No recipients have been specified
            throw new MailPreparationException("No recipient has been specified for the mail action");
        }
    }
    return recipients.values();
}

From source file:com.qcadoo.mail.internal.MailServiceImpl.java

protected void sendHtmlTextEmail(final String sender, final String recipient, final String subject,
        final String body) {
    validateEmail(sender);// ww w.ja  v a  2s  .co m
    validateEmail(recipient);
    Preconditions.checkArgument(StringUtils.isNotBlank(subject), "e-mail subject should not be blank");
    Preconditions.checkArgument(StringUtils.isNotBlank(body), "e-mail body should not be blank");

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

    try {
        mimeMessageHelper.setFrom(sender);
        mimeMessageHelper.setTo(recipient);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(body, true);
    } catch (MessagingException e) {
        throw new MailPreparationException(e);
    }

    mailSender.send(mimeMessage);
}

From source file:org.alfresco.repo.action.executer.MailActionExecuter.java

public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef,
        final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) {
    // Create the mime mail message.
    // Hack: using an array here to get around the fact that inner classes aren't closures.
    // The MimeMessagePreparator.prepare() signature does not allow us to return a value and yet
    // we can't set a result on a bare, non-final object reference due to Java language restrictions.
    final MimeMessageHelper[] messageRef = new MimeMessageHelper[1];
    MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
        @SuppressWarnings("unchecked")
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            if (logger.isDebugEnabled()) {
                logger.debug(ruleAction.getParameterValues());
            }/*  w w w  .j  a  va  2  s . c  o  m*/

            messageRef[0] = new MimeMessageHelper(mimeMessage);

            // set header encoding if one has been supplied
            if (headerEncoding != null && headerEncoding.length() != 0) {
                mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding);
            }

            // set recipient
            String to = (String) ruleAction.getParameterValue(PARAM_TO);
            if (to != null && to.length() != 0) {
                messageRef[0].setTo(to);

                // Note: there is no validation on the username to check that it actually is an email address.
                // TODO Fix this.

                Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC);
                if (ccValue != null) {
                    if (ccValue instanceof String) {
                        String cc = (String) ccValue;
                        if (cc.length() > 0) {
                            messageRef[0].setCc(cc);
                        }

                    } else if (ccValue instanceof List<?>) {
                        List<String> s = (List<String>) ccValue;
                        messageRef[0].setCc((String[]) s.toArray());
                    } else if (ccValue.getClass().isArray()) {
                        messageRef[0].setCc((String[]) ccValue);
                    }

                }
                Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC);
                if (bccValue != null) {
                    if (bccValue instanceof String) {
                        String bcc = (String) bccValue;
                        if (bcc.length() > 0) {
                            messageRef[0].setBcc(bcc);
                        }

                    } else if (bccValue instanceof List<?>) {
                        List<String> s = (List<String>) bccValue;
                        messageRef[0].setBcc((String[]) s.toArray());
                    } else if (bccValue.getClass().isArray()) {
                        messageRef[0].setCc((String[]) bccValue);
                    }
                }

            } else {
                // see if multiple recipients have been supplied - as a list of authorities
                Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY);
                List<String> authorities = null;
                if (authoritiesValue != null) {
                    if (authoritiesValue instanceof String) {
                        authorities = new ArrayList<String>(1);
                        authorities.add((String) authoritiesValue);
                    } else {
                        authorities = (List<String>) authoritiesValue;
                    }
                }

                if (authorities != null && authorities.size() != 0) {
                    List<String> recipients = new ArrayList<String>(authorities.size());

                    if (logger.isTraceEnabled()) {
                        logger.trace(authorities.size() + " recipient(s) for mail");
                    }

                    for (String authority : authorities) {
                        final AuthorityType authType = AuthorityType.getAuthorityType(authority);

                        if (logger.isTraceEnabled()) {
                            logger.trace(" authority type: " + authType);
                        }

                        if (authType.equals(AuthorityType.USER)) {
                            if (personService.personExists(authority) == true) {
                                NodeRef person = personService.getPerson(authority);

                                if (!personService.isEnabled(authority)
                                        && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) {
                                    continue;
                                }

                                String address = (String) nodeService.getProperty(person,
                                        ContentModel.PROP_EMAIL);
                                if (address != null && address.length() != 0 && validateAddress(address)) {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace("Recipient (person) exists in Alfresco with known email.");
                                    }
                                    recipients.add(address);
                                } else {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace(
                                                "Recipient (person) exists in Alfresco without known email.");
                                    }
                                    // If the username looks like an email address, we'll use that.
                                    if (validateAddress(authority)) {
                                        recipients.add(authority);
                                    }
                                }
                            } else {
                                if (logger.isTraceEnabled()) {
                                    logger.trace("Recipient does not exist in Alfresco.");
                                }
                                if (validateAddress(authority)) {
                                    recipients.add(authority);
                                }
                            }
                        } else if (authType.equals(AuthorityType.GROUP)
                                || authType.equals(AuthorityType.EVERYONE)) {
                            if (logger.isTraceEnabled()) {
                                logger.trace("Recipient is a group...");
                            }
                            // Notify all members of the group
                            Set<String> users;
                            if (authType.equals(AuthorityType.GROUP)) {
                                users = authorityService.getContainedAuthorities(AuthorityType.USER, authority,
                                        false);
                            } else {
                                users = authorityService.getAllAuthorities(AuthorityType.USER);
                            }

                            for (String userAuth : users) {
                                if (personService.personExists(userAuth) == true) {
                                    if (!personService.isEnabled(userAuth)) {
                                        continue;
                                    }
                                    NodeRef person = personService.getPerson(userAuth);
                                    String address = (String) nodeService.getProperty(person,
                                            ContentModel.PROP_EMAIL);
                                    if (address != null && address.length() != 0) {
                                        recipients.add(address);
                                        if (logger.isTraceEnabled()) {
                                            logger.trace("   Group member email is known.");
                                        }
                                    } else {
                                        if (logger.isTraceEnabled()) {
                                            logger.trace("   Group member email not known.");
                                        }
                                        if (validateAddress(authority)) {
                                            recipients.add(userAuth);
                                        }
                                    }
                                } else {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace("   Group member person not found");
                                    }
                                    if (validateAddress(authority)) {
                                        recipients.add(userAuth);
                                    }
                                }
                            }
                        }
                    }

                    if (logger.isTraceEnabled()) {
                        logger.trace(recipients.size() + " valid recipient(s).");
                    }

                    if (recipients.size() > 0) {
                        messageRef[0].setTo(recipients.toArray(new String[recipients.size()]));
                    } else {
                        // All recipients were invalid
                        throw new MailPreparationException("All recipients for the mail action were invalid");
                    }
                } else {
                    // No recipients have been specified
                    throw new MailPreparationException("No recipient has been specified for the mail action");
                }
            }

            // from person - not to be performed for the "admin" or "system" users
            NodeRef fromPerson = null;

            final String currentUserName = authService.getCurrentUserName();

            final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] {
                    AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() });
            if (!usersNotToBeUsedInFromField.contains(currentUserName)) {
                fromPerson = personService.getPerson(currentUserName);
            }

            if (isFromEnabled()) {
                // Use the FROM parameter in preference to calculating values.
                String from = (String) ruleAction.getParameterValue(PARAM_FROM);
                if (from != null && from.length() > 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("from specified as a parameter, from:" + from);
                    }

                    // Check whether or not to use a personal name for the email (will be RFC 2047 encoded)
                    String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME);
                    if (fromPersonalName != null && fromPersonalName.length() > 0) {
                        try {
                            messageRef[0].setFrom(from, fromPersonalName);
                        } catch (UnsupportedEncodingException error) {
                            // Uses the JVM's default encoding, can never be unsupported. Just in case, revert to simple email
                            messageRef[0].setFrom(from);
                        }
                    } else {
                        messageRef[0].setFrom(from);
                    }
                } else {
                    // set the from address from the current user
                    String fromActualUser = null;
                    if (fromPerson != null) {
                        fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL);
                    }

                    if (fromActualUser != null && fromActualUser.length() != 0) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("looked up email address for :" + fromPerson + " email from "
                                    + fromActualUser);
                        }
                        messageRef[0].setFrom(fromActualUser);
                    } else {
                        // from system or user does not have email address
                        messageRef[0].setFrom(fromDefaultAddress);
                    }
                }

            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("from not enabled - sending from default address:" + fromDefaultAddress);
                }
                // from is not enabled.
                messageRef[0].setFrom(fromDefaultAddress);
            }

            // set subject line
            messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

            if ((testModeRecipient != null) && (testModeRecipient.length() > 0)
                    && (!testModeRecipient.equals("${dev.email.recipient.address}"))) {
                // If we have an override for the email recipient, we'll send the email to that address instead.
                // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way.
                messageRef[0].setTo(testModeRecipient);

                String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO);
                if (emailRecipient == null) {
                    Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
                    if (obj != null) {
                        emailRecipient = obj.toString();
                    }
                }

                String recipientPrefixedSubject = "(" + emailRecipient + ") "
                        + (String) ruleAction.getParameterValue(PARAM_SUBJECT);

                messageRef[0].setSubject(recipientPrefixedSubject);
            }

            // See if an email template has been specified
            String text = null;

            // templateRef: either a nodeRef or classpath (see ClasspathRepoTemplateLoader)
            Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE);
            String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref);
            if (templateRef != null) {
                Map<String, Object> suppliedModel = null;
                if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) {
                    Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL);
                    if (m instanceof Map) {
                        suppliedModel = (Map<String, Object>) m;
                    } else {
                        logger.warn("Skipping unsupported email template model parameters of type "
                                + m.getClass().getName() + " : " + m.toString());
                    }
                }

                // build the email template model
                Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel,
                        fromPerson);

                // Determine the locale to use to send the email.
                Locale locale = recipient.getSecond();
                if (locale == null) {
                    locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE);
                }
                if (locale == null) {
                    locale = sender.getSecond();
                }

                // set subject line
                String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT);
                Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS);
                Object[] subjectParams = null;
                //Javasctipt pass SubjectParams as ArrayList. see MNT-12534 
                if (subjectParamsObject instanceof List) {
                    subjectParams = ((List<Object>) subjectParamsObject).toArray();
                } else if (subjectParamsObject instanceof Object[]) {
                    subjectParams = (Object[]) subjectParamsObject;
                } else {
                    if (subjectParamsObject != null) {
                        subjectParams = new Object[] { subjectParamsObject.toString() };
                    }
                }
                String localizedSubject = getLocalizedSubject(subject, subjectParams, locale);
                if (locale == null) {
                    // process the template against the model
                    text = templateService.processTemplate("freemarker", templateRef, model);
                } else {
                    // process the template against the model
                    text = templateService.processTemplate("freemarker", templateRef, model, locale);
                }
                if ((testModeRecipient != null) && (testModeRecipient.length() > 0)
                        && (!testModeRecipient.equals("${dev.email.recipient.address}"))) {
                    // If we have an override for the email recipient, we'll send the email to that address instead.
                    // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way.
                    messageRef[0].setTo(testModeRecipient);

                    String emailRecipient = recipient.getFirst();

                    String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject;

                    messageRef[0].setSubject(recipientPrefixedSubject);
                } else {
                    messageRef[0].setTo(recipient.getFirst());
                    messageRef[0].setSubject(localizedSubject);
                }
            }

            // set the text body of the message

            boolean isHTML = false;
            if (text == null) {
                text = (String) ruleAction.getParameterValue(PARAM_TEXT);
            }

            if (text != null) {
                if (isHTML(text)) {
                    isHTML = true;
                }
            } else {
                text = (String) ruleAction.getParameterValue(PARAM_HTML);
                if (text != null) {
                    // assume HTML
                    isHTML = true;
                }
            }

            if (text != null) {
                messageRef[0].setText(text, isHTML);
            }

        }
    };
    MimeMessage mimeMessage = mailService.createMimeMessage();
    try {
        mailPreparer.prepare(mimeMessage);
    } catch (Exception e) {
        // We're forced to catch java.lang.Exception here. Urgh.
        if (logger.isWarnEnabled()) {
            logger.warn("Unable to prepare mail message. Skipping.", e);
        }
        return null;
    }

    return messageRef[0];
}

From source file:org.alfresco.repo.action.executer.MailActionExecuter.java

@SuppressWarnings("unchecked")
private Collection<Pair<String, Locale>> getRecipients(Action ruleAction) {
    Map<String, Pair<String, Locale>> recipients = new HashMap<String, Pair<String, Locale>>();

    // set recipient
    String to = (String) ruleAction.getParameterValue(PARAM_TO);
    if (to != null && to.length() != 0) {
        Locale locale = null;//from   w  ww . j  av a  2s  .co m
        if (personExists(to)) {
            locale = getLocaleForUser(to);
        }
        recipients.put(to, new Pair<String, Locale>(to, locale));
    } else {
        // see if multiple recipients have been supplied - as a list of authorities
        Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY);
        List<String> authorities = null;
        if (authoritiesValue != null) {
            if (authoritiesValue instanceof String) {
                authorities = new ArrayList<String>(1);
                authorities.add((String) authoritiesValue);
            } else {
                authorities = (List<String>) authoritiesValue;
            }
        }

        if (authorities != null && authorities.size() != 0) {
            for (String authority : authorities) {
                AuthorityType authType = AuthorityType.getAuthorityType(authority);
                if (authType.equals(AuthorityType.USER)) {
                    // Formerly, this code checked personExists(auth) but we now support emailing addresses who are not yet Alfresco users.
                    // Check the user name to be a valid email and we don't need to log an error in this case
                    // ALF-19231
                    // Validate the email, allowing for local email addresses
                    if ((authority != null) && (authority.length() != 0)
                            && (!recipients.containsKey(authority))) {
                        if (personExists(authority)) {
                            String address = getPersonEmail(authority);
                            if (address != null && address.length() != 0 && validateAddress(address)) {
                                Locale locale = getLocaleForUser(authority);
                                recipients.put(authority, new Pair<String, Locale>(address, locale));
                            } else {
                                EmailValidator emailValidator = EmailValidator.getInstance(true);
                                if (validateAddresses && emailValidator.isValid(authority)) {
                                    Locale locale = getLocaleForUser(authority);
                                    recipients.put(authority, new Pair<String, Locale>(authority, locale));
                                }
                            }
                        } else {
                            recipients.put(authority, new Pair<String, Locale>(authority, null));
                        }
                    }
                } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) {
                    // Notify all members of the group
                    Set<String> users;
                    if (authType.equals(AuthorityType.GROUP)) {
                        users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false);
                    } else {
                        users = authorityService.getAllAuthorities(AuthorityType.USER);
                    }

                    for (String userAuth : users) {
                        if (recipients.containsKey(userAuth)) {
                            continue;
                        }
                        if (personExists(userAuth)) {
                            // Check the user name to be a valid email and we don't need to log an error in this case
                            // ALF-19231
                            // Validate the email, allowing for local email addresses
                            String address = getPersonEmail(userAuth);
                            if (address != null && address.length() != 0 && validateAddress(address)) {
                                Locale locale = getLocaleForUser(userAuth);
                                recipients.put(userAuth, new Pair<String, Locale>(address, locale));
                            } else {
                                EmailValidator emailValidator = EmailValidator.getInstance(true);
                                if (validateAddresses && emailValidator.isValid(userAuth)) {
                                    if (userAuth != null && userAuth.length() != 0) {
                                        Locale locale = getLocaleForUser(userAuth);
                                        recipients.put(userAuth, new Pair<String, Locale>(userAuth, locale));
                                    }
                                }
                            }
                        } else {
                            recipients.put(userAuth, new Pair<String, Locale>(authority, null));
                        }
                    }
                }
            }
            if (recipients.size() <= 0) {
                // All recipients were invalid
                throw new MailPreparationException("All recipients for the mail action were invalid");
            }
        } else {
            // No recipients have been specified
            throw new MailPreparationException("No recipient has been specified for the mail action");
        }
    }
    return recipients.values();
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
    try {//www.  j a va2  s  .  c o m
        List mimeMessages = new ArrayList(mimeMessagePreparators.length);
        for (int i = 0; i < mimeMessagePreparators.length; i++) {
            MimeMessage mimeMessage = createMimeMessage();
            mimeMessagePreparators[i].prepare(mimeMessage);
            mimeMessages.add(mimeMessage);
        }
        send((MimeMessage[]) mimeMessages.toArray(new MimeMessage[mimeMessages.size()]));
    } catch (MailException ex) {
        throw ex;
    } catch (MessagingException ex) {
        throw new MailParseException(ex);
    } catch (IOException ex) {
        throw new MailPreparationException(ex);
    } catch (Exception ex) {
        throw new MailPreparationException(ex);
    }
}