Example usage for org.springframework.mail.javamail MimeMessagePreparator prepare

List of usage examples for org.springframework.mail.javamail MimeMessagePreparator prepare

Introduction

In this page you can find the example usage for org.springframework.mail.javamail MimeMessagePreparator prepare.

Prototype

void prepare(MimeMessage mimeMessage) throws Exception;

Source Link

Document

Prepare the given new MimeMessage instance.

Usage

From source file:org.jrecruiter.mock.MockJavaMailSender.java

@Override
public void send(MimeMessagePreparator preparator) throws MailException {

    message = new MimeMessage((Session) null);
    try {/*ww  w .ja v a2s .  c om*/
        preparator.prepare(message);
    } catch (Exception e) {
        throw new IllegalStateException("Error while preparing message.", e);
    }

    LOGGER.info("send() - Mock message successfully sent.");

}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }//from  www.j a  v  a  2 s. c o  m
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}

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());
            }/*www  .j ava2  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: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());
            }//from   w w w  .ja v  a  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.broadleafcommerce.common.email.service.LoggingMailSender.java

@Override
public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
    for (MimeMessagePreparator preparator : mimeMessagePreparators) {
        try {// w w  w. j  av  a  2  s  .co  m
            MimeMessage mimeMessage = createMimeMessage();
            preparator.prepare(mimeMessage);
            LOG.info("\"Sending\" email: ");
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart msg = (MimeMultipart) mimeMessage.getContent();
                DataHandler dh = msg.getBodyPart(0).getDataHandler();
                ByteArrayOutputStream baos = null;
                try {
                    baos = new ByteArrayOutputStream();
                    dh.writeTo(baos);
                } catch (Exception e) {
                    // Do nothing
                } finally {
                    try {
                        baos.close();
                    } catch (Exception e) {
                        LOG.error("Couldn't close byte array output stream");
                    }
                }
            } else {
                LOG.info(mimeMessage.getContent());
            }
        } catch (Exception e) {
            LOG.error("Could not create message", e);
        }
    }
}