Example usage for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper

List of usage examples for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper

Introduction

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

Prototype

public MimeMessageHelper(MimeMessage mimeMessage) 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e.

Usage

From source file:it.jugpadova.blo.JuggerBo.java

/**
 * General jugger mail sender//from ww w.j  av  a2 s.  c  o m
 *
 * @param jugger
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Jugger jugger, final String baseUrl, final String subject, final String oneWayCode,
        final String template) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(jugger.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("jugger", jugger);
            model.put("baseUrl", baseUrl);
            model.put("oneWayCode", URLEncoder.encode(oneWayCode, "UTF-8"));
            model.put("username", URLEncoder.encode(jugger.getUser().getUsername(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}

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());
            }//  w  w  w .  ja v  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:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/app", method = RequestMethod.POST)
public String registerApp(ModelMap model, @ModelAttribute("application") Application application,
        @RequestParam("certificate") MultipartFile certificate, MultipartFile icon, BindingResult result,
        Authentication authentication) throws IOException {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());/*  www .j av a 2 s.c  om*/

    if (developer == null) {
        return "redirect:register_developer";
    } else {

        applicationValidator.validate(application, result);

        application.setRegistrationDate(new Date());
        application.setState(State.REGISTRATED);

        application.setDeveloper(developer);

        Application existingApp = appManagement.getApplicationByClientId(application.getClientId());

        if (existingApp != null) {
            result.rejectValue("clientId", "invalid.clientId",
                    "Klient id:et finns redan registrerat, var god vlj ett annat.");
        }

        // validate icon if it exists
        if (application.getIcon() != null && application.getIcon().length > 0) {
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon());
                BufferedImage bufferedImage = ImageIO.read(bis);
                log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight());
                application.setIconContentType(icon.getContentType());
                // TODO: Check width and height here!
            } catch (Exception e) {
                result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig");
            }
        }

        //For now we are just allowing the addition of just one certificate
        List<Certificate> certs = new ArrayList<>();

        if (certificate != null && certificate.getSize() > 0) {
            certs.add(createCertificate(certificate, result));
        }

        if (result.hasErrors()) {
            List<Permission> permissions = permissionServices.getAllPermissions();
            model.addAttribute("scopes", permissions);
            return "register_application";
        }

        Application savedApp = appManagement.registerApplication(application);

        for (Certificate cert : certs) {
            cert.setApplication(savedApp);
            appManagement.saveCertificate(cert);
            savedApp.getCertificates().add(cert);
        }

        try {
            log.debug("Composing message to: {}", mailAddress);
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            helper.setTo(mailAddress);
            helper.setFrom(new InternetAddress(mailFrom));

            log.debug("Creating message for existing app. User {} edited the app {}",
                    citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());
            helper.setSubject("Redigerad app: " + application.getName());
            helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: "
                    + application.getName());

            log.debug("Sending mail notification.");
            sender.send(message);
        } catch (Exception e) {
            log.error("Caught exception while trying to send email", e);
        }

        return "redirect:";
    }
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/app", params = { "delete" })
public ModelAndView deleteApp(@RequestParam("delete") Long id, Authentication authentication) {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());

    log.debug("User {} deleted the app with id {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), id);

    if (developer == null) {
        return new ModelAndView("redirect:register_developer");
    } else {/*from ww  w  . j ava  2 s  . co m*/
        Application application = appManagement.getApplication(id);
        log.debug("Deleting the app {}.", application.getName());

        if (application.getDeveloper().getResidentIdentificationNumber().equals(user.getUsername())) {
            appManagement.removeApplication(id);

            try {
                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message);

                helper.setTo(mailAddress);
                helper.setFrom(new InternetAddress(mailFrom));
                helper.setSubject("Borttagen app: " + application.getName());
                helper.setText("Utvecklare med personnr " + user.getUsername() + " har tagit bort appen: "
                        + application.getName());
                sender.send(message);
            } catch (Exception e) {
                log.error("Caught exception while trying to send email", e);
            }

        } else {
            throw new RuntimeException(
                    "The logged in user is not the same as the developer of the application!");
        }

        return new ModelAndView("redirect:");
    }
}

From source file:it.jugpadova.blo.EventBo.java

private void sendConfirmationEmail(final Event event, final Participant participant, final String baseUrl) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject("Please confirm event registration");
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("event", event);
            model.put("baseUrl", baseUrl);
            model.put("confirmationCode", URLEncoder.encode(participant.getConfirmationCode(), "UTF-8"));
            model.put("email", URLEncoder.encode(participant.getEmail(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "it/jugpadova/registration-confirmation.vm", model);
            message.setText(text, true);
        }/*w ww. jav  a  2  s. com*/
    };
    this.mailSender.send(preparator);
}

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(simpleMailMessage.getTo());

            // The "from" field is required
            if (simpleMailMessage.getFrom() == null) {
                simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL);
            }//from   w  w w . ja v a 2  s .  c  om

            message.setFrom(simpleMailMessage.getFrom());
            message.setSubject(simpleMailMessage.getSubject());

            // Map all the fields for the email template
            Map<String, Object> model = new HashMap<String, Object>();

            // Add the host name into the footer of the email
            String host = InetAddress.getLocalHost().getHostName();

            // Message title
            model.put("title", "Message from The ARK");
            // Message header
            model.put("header", "Message from The ARK");
            // Message subject
            model.put("subject", simpleMailMessage.getSubject());
            // Message text
            model.put("text", simpleMailMessage.getText());
            // Hostname in message footer
            model.put("host", host);

            // TODO: Add inline image(s)??
            // Add inline image header
            // FileSystemResource res = new FileSystemResource(new
            // File("c:/Sample.jpg"));
            // message.addInline("bgHeaderImg", res);

            // Set up the email text
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "au/org/theark/core/velocity/resetPasswordEmail.vm", model);
            message.setText(text, true);
        }
    };

    // send out the email
    javaMailSender.send(preparator);
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Sends the notification by email.//from   w  w w.ja  v a  2 s.  com
 * <p/>
 * This method does not throw any exception.
 *
 * @param mailMessage The message of the mail.
 * @param mailSubject The subject of the email.
 * @param processType The name of the current processor. It is used to distinguish the recipient of the email.
 */
private void notifyByEmail(String mailMessage, String mailSubject, String processType) {
    mailMessage = mailMessage.replace("@#$%EndingTime%$#@",
            DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(new Date()));

    String recipient = processType.equals("BillProcessing") ? billMailRecipient : generalMailRecipient;

    logger.info(
            "Send email to " + recipient + ", subject = [" + mailSubject + "]. Message:" + CRLF + mailMessage);

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {
        helper.setTo(recipient);

        helper.setSubject(mailSubject);

        helper.setText(mailMessage);

        mailSender.send(message);
    } catch (MessagingException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    } catch (MailSendException e) {
        logger.error("Error sending email to " + recipient + ", subject = [" + mailSubject + "].", e);
    }
}

From source file:ome.services.mail.MailUtil.java

/**
 * Main method which takes typical email fields as arguments, to prepare and
 * populate the given new MimeMessage instance and send.
 *
 * @param from/*from w  w w .  java  2  s.co  m*/
 *            email address message is sent from
 * @param to
 *            email address message is sent to
 * @param topic
 *            topic of the message
 * @param body
 *            body of the message
 * @param html
 *            flag determines the content type to apply.
 * @param ccrecipients
 *            list of email addresses message is sent as copy to
 * @param bccrecipients
 *            list of email addresses message is sent as blind copy to
 */
public void sendEmail(final String from, final String to, final String topic, final String body,
        final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setText(body, html);
            message.setFrom(from);
            message.setSubject(topic);
            message.setTo(to);
            if (ccrecipients != null && !ccrecipients.isEmpty()) {
                message.setCc(ccrecipients.toArray(new String[ccrecipients.size()]));
            }

            if (bccrecipients != null && !bccrecipients.isEmpty()) {
                message.setCc(bccrecipients.toArray(new String[bccrecipients.size()]));
            }
        }

    };

    this.mailSender.send(preparator);
}

From source file:org.akaza.openclinica.controller.SystemController.java

public String sendEmail(JavaMailSenderImpl mailSender, String emailSubject, String message)
        throws OpenClinicaSystemException {

    logger.info("Sending email...");
    try {//www .j  a va2s  .  c o  m
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(EmailEngine.getAdminEmail());
        helper.setTo("oc123@openclinica.com");
        helper.setSubject(emailSubject);
        helper.setText(message);

        mailSender.send(mimeMessage);
        return "ACTIVE";
    } catch (MailException me) {
        return "INACTIVE";
    } catch (MessagingException me) {
        return "INACTIVE";
    }
}

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   ww  w  . j av 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];
}