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

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

Introduction

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

Prototype

public void setTo(String[] to) throws MessagingException 

Source Link

Usage

From source file:org.alfresco.web.bean.TemplateMailHelperBean.java

/**
 * Send an email notification to the specified User authority
 * // w  ww  .  ja v a2 s .  c o  m
 * @param person     Person node representing the user
 * @param node       Node they are invited too
 * @param from       From text message
 * @param roleText   The role display label for the user invite notification
 */
public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) {
    final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL);

    if (to != null && to.length() != 0) {
        String body = this.body;
        if (this.usingTemplate != null) {
            FacesContext fc = FacesContext.getCurrentInstance();

            // use template service to format the email
            NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate);
            ServiceRegistry services = Repository.getServiceRegistry(fc);
            Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services,
                    Application.getCurrentUser(fc), templateRef);
            model.put("role", roleText);
            model.put("space", node);
            // object to allow client urls to be generated in emails
            model.put("url", new BaseTemplateContentServlet.URLHelper(fc));
            model.put("msg", new I18NMessageMethod());
            model.put("document", node);
            if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) {
                NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef();
                if (parentNodeRef == null) {
                    throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node);
                }
                model.put("space", parentNodeRef);
            }
            model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams()));

            body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model);
        }
        this.finalBody = body;

        MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(to);
                message.setSubject(subject);
                message.setText(finalBody, MailActionExecuter.isHTML(finalBody));
                message.setFrom(from);
            }
        };

        if (logger.isDebugEnabled())
            logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject
                    + "\n...with body:\n" + body);

        try {
            // Send the message
            this.getMailSender().send(mailPreparer);
        } catch (Throwable e) {
            // don't stop the action but let admins know email is not getting sent
            logger.error("Failed to send email to " + to, e);
        }
    }
}

From source file:org.apache.syncope.core.logic.notification.NotificationJob.java

public TaskExec executeSingle(final NotificationTask task) {
    init();//from   w  w  w.ja  v a2 s.  c  o m

    TaskExec execution = entityFactory.newEntity(TaskExec.class);
    execution.setTask(task);
    execution.setStartDate(new Date());

    boolean retryPossible = true;

    if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for sending e-mails:\n"
                + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n"
                + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(Status.NOT_SENT.name());
        retryPossible = false;

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n"
                    + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                mailSender.send(message);

                execution.setStatus(Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        Result.SUCCESS, null, null, task, "Successfully sent notification to " + to);
            } catch (Exception e) {
                LOG.error("Could not send e-mail", e);

                execution.setStatus(Status.NOT_SENT.name());
                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
                    execution.setMessage(ExceptionUtils2.getFullStackTrace(e));
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        Result.FAILURE, null, null, task, "Could not send notification to " + to, e);
            }

            execution.setEndDate(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = notificationManager.storeExec(execution);
        if (retryPossible && (Status.valueOf(execution.getStatus()) == Status.NOT_SENT)) {
            handleRetries(execution);
        }
    } else {
        notificationManager.setTaskExecuted(execution.getTask().getKey(), true);
    }

    return execution;
}

From source file:org.apache.syncope.core.logic.notification.NotificationJobDelegate.java

@Transactional
public TaskExec executeSingle(final NotificationTask task) {
    init();// w w  w.j  a va 2  s  .c o m

    TaskExec execution = entityFactory.newEntity(TaskExec.class);
    execution.setTask(task);
    execution.setStart(new Date());

    boolean retryPossible = true;

    if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for sending e-mails:\n"
                + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n"
                + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(NotificationJob.Status.NOT_SENT.name());
        retryPossible = false;

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n"
                    + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                mailSender.send(message);

                execution.setStatus(NotificationJob.Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        AuditElements.Result.SUCCESS, null, null, task,
                        "Successfully sent notification to " + to);
            } catch (Exception e) {
                LOG.error("Could not send e-mail", e);

                execution.setStatus(NotificationJob.Status.NOT_SENT.name());
                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
                    execution.setMessage(ExceptionUtils2.getFullStackTrace(e));
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        AuditElements.Result.FAILURE, null, null, task, "Could not send notification to " + to,
                        e);
            }

            execution.setEnd(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = notificationManager.storeExec(execution);
        if (retryPossible
                && (NotificationJob.Status.valueOf(execution.getStatus()) == NotificationJob.Status.NOT_SENT)) {

            handleRetries(execution);
        }
    } else {
        notificationManager.setTaskExecuted(execution.getTask().getKey(), true);
    }

    return execution;
}

From source file:org.apache.syncope.core.notification.NotificationJob.java

public TaskExec executeSingle(final NotificationTask task) {
    init();//www. ja v a2 s .  com

    TaskExec execution = new TaskExec();
    execution.setTask(task);
    execution.setStartDate(new Date());

    boolean retryPossible = true;

    if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for sending e-mails:\n"
                + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n"
                + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(Status.NOT_SENT.name());
        retryPossible = false;

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n"
                    + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                mailSender.send(message);

                execution.setStatus(Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        Result.SUCCESS, null, null, task, "Successfully sent notification to " + to);
            } catch (Exception e) {
                LOG.error("Could not send e-mail", e);

                execution.setStatus(Status.NOT_SENT.name());
                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
                    execution.setMessage(ExceptionUtil.getFullStackTrace(e));
                }

                auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send",
                        Result.FAILURE, null, null, task, "Could not send notification to " + to, e);
            }

            execution.setEndDate(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = notificationManager.storeExec(execution);
        if (retryPossible && (Status.valueOf(execution.getStatus()) == Status.NOT_SENT)) {
            handleRetries(execution);
        }
    } else {
        notificationManager.setTaskExecuted(execution.getTask().getId(), true);
    }

    return execution;
}

From source file:org.apache.syncope.core.provisioning.java.job.notification.NotificationJobDelegate.java

@Transactional
public TaskExec executeSingle(final NotificationTask task) {
    TaskExec execution = entityFactory.newEntity(TaskExec.class);
    execution.setTask(task);/*from  w  ww  .j av a2s  . co  m*/
    execution.setStart(new Date());

    boolean retryPossible = true;

    if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for sending e-mails:\n"
                + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n"
                + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(NotificationJob.Status.NOT_SENT.name());
        retryPossible = false;

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n"
                    + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                mailSender.send(message);

                execution.setStatus(NotificationJob.Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }

                notificationManager.createTasks(AuditElements.EventCategoryType.TASK, "notification", null,
                        "send", AuditElements.Result.SUCCESS, null, null, task,
                        "Successfully sent notification to " + to);
            } catch (Exception e) {
                LOG.error("Could not send e-mail", e);

                execution.setStatus(NotificationJob.Status.NOT_SENT.name());
                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {
                    execution.setMessage(ExceptionUtils2.getFullStackTrace(e));
                }

                notificationManager.createTasks(AuditElements.EventCategoryType.TASK, "notification", null,
                        "send", AuditElements.Result.FAILURE, null, null, task,
                        "Could not send notification to " + to, e);
            }

            execution.setEnd(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = notificationManager.storeExec(execution);
        if (retryPossible
                && (NotificationJob.Status.valueOf(execution.getStatus()) == NotificationJob.Status.NOT_SENT)) {

            handleRetries(execution);
        }
    } else {
        notificationManager.setTaskExecuted(execution.getTask().getKey(), true);
    }

    return execution;
}

From source file:org.broadleafcommerce.common.email.service.message.MessageCreator.java

public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override//ww  w.  j a v a  2s.c o m
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(),
                        attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImpl.java

protected MimeMessage createMessage(String from, String[] to, String[] cc, String[] bcc, String replyTo,
        String subject, String body, boolean html, File... attachments) throws EmailException {
    boolean addAttachments = ArrayUtils.isNotEmpty(attachments);
    MimeMessageHelper messageHelper;

    try {/*  w  w w . j  ava2s.co  m*/
        if (addAttachments) {
            messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
        } else {
            messageHelper = new MimeMessageHelper(mailSender.createMimeMessage());
        }

        messageHelper.setFrom(from);
        if (to != null) {
            messageHelper.setTo(to);
        }
        if (cc != null) {
            messageHelper.setCc(cc);
        }
        if (bcc != null) {
            messageHelper.setBcc(bcc);
        }
        if (replyTo != null) {
            messageHelper.setReplyTo(replyTo);
        }
        messageHelper.setSubject(subject);
        messageHelper.setText(body, html);

        if (addAttachments) {
            for (File attachment : attachments) {
                messageHelper.addAttachment(attachment.getName(), attachment);
            }
        }
    } catch (AddressException e) {
        throw new EmailAddressException(e);
    } catch (MessagingException e) {
        throw new EmailPreparationException(e);
    }

    logger.debug(LOG_KEY_MIME_MSG_CREATED, from, StringUtils.join(to, ','), StringUtils.join(cc, ','),
            StringUtils.join(bcc, ','), subject, body);

    return messageHelper.getMimeMessage();
}

From source file:org.craftercms.social.services.system.EmailService.java

public void sendEmail(final Profile toSend, final StringWriter writer, final String subject,
        final String contextId) throws SocialException {
    Map<String, Object> emailSettings = getEmailSettings(contextId);
    JavaMailSender sender = getSender(contextId);
    MimeMessage message = sender.createMimeMessage();
    String realSubject = subject;
    if (StringUtils.isBlank(realSubject)) {
        realSubject = generateSubjectString(emailSettings.get("subject").toString());
    }/*w ww .  j  a  v  a2  s  .c o m*/
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(toSend.getEmail());
        helper.setReplyTo(emailSettings.get("replyTo").toString());
        helper.setFrom(emailSettings.get("from").toString());
        helper.setSubject(realSubject);

        helper.setPriority(NumberUtils.toInt(emailSettings.get("priority").toString(), 4));
        helper.setText(writer.toString(), true);
        message.setHeader("Message-ID", String.format("[%s]-%s-%s-%s", RandomStringUtils.randomAlphanumeric(5),
                contextId, realSubject, toSend.getId()));
        sender.send(message);
    } catch (MessagingException e) {
        throw new SocialException("Unable to send Email to " + toSend.getEmail(), e);
    }
}

From source file:org.devproof.portal.core.module.email.service.EmailServiceImpl.java

@Override
@Transactional(readOnly = true)/* w  ww .  j ava  2s . c  o  m*/
public void sendEmail(EmailTemplate template, EmailPlaceholderBean placeholder) {
    if (emailDisabled) {
        System.out.println("Sending Email <" + placeholder.getToEmail() + ">: " + template.getSubject());
        return;
    }
    // Create email
    try {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        if (placeholder.getContactEmail() != null) {
            String from = "";
            if (placeholder.getContactFullname() != null) {
                from += placeholder.getContactFullname();
            } else {
                from += placeholder.getContactEmail();
            }
            from += " <" + placeholder.getContactEmail() + ">";
            helper.setFrom(from);
        } else {
            String from = configurationService.findAsString(EmailConstants.CONF_FROM_EMAIL_NAME);
            from += " <" + configurationService.findAsString(EmailConstants.CONF_FROM_EMAIL_ADDRESS) + ">";
            helper.setFrom(from);
        }
        if (placeholder.getToEmail() != null) {
            String name = placeholder.getToFirstname() != null ? placeholder.getToFirstname() : "";
            name += " " + (placeholder.getToLastname() != null ? placeholder.getToLastname() : "");
            if (StringUtils.isBlank(name)) {
                name = placeholder.getToUsername();
            }
            helper.setTo(name + " <" + placeholder.getToEmail() + ">");
        } else {
            String name = placeholder.getFirstname() != null ? placeholder.getFirstname() : "";
            name += " " + (placeholder.getLastname() != null ? placeholder.getLastname() : "");
            if (StringUtils.isBlank(name)) {
                name = placeholder.getUsername();
            }
            helper.setTo(name + " <" + placeholder.getEmail() + ">");
        }
        helper.setSubject(replace(template.getSubject(), placeholder));
        helper.setText("<html><body>" + replace(template.getContent(), placeholder) + "</body></html>", true);
        javaMailSender.send(msg);
        logger.info("Send email to " + placeholder.getToEmail() + " " + template.getSubject());
    } catch (MailException e) {
        throw new UnhandledException(e);
    } catch (MessagingException e) {
        throw new UnhandledException(e);
    }
}

From source file:org.emmanet.controllers.requestsUpdateInterfaceFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, Exception {
    model.put("BASEURL", BASEURL);
    System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL"));
    WebRequestsDAO webRequest = (WebRequestsDAO) command;

    if (!request.getParameter("noTAinfo").equals("true")) {
        String panelDecision = webRequest.getTa_panel_decision();

        String applicationType = webRequest.getApplication_type();

        if (panelDecision.equals("yes") || panelDecision.equals("no") && applicationType.contains("ta")) {
            //check if mail already sent by checking notes for string
            if (!webRequest.getNotes().contains("TA mail sent")) {

                //Decision has been made therefore decision mails should be triggered
                //SimpleMailMessage msg = getSimpleMailMessage();
                MimeMessage msg = getJavaMailSender().createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
                String content = "";
                String toAddress = webRequest.getSci_e_mail();
                // msg.setTo(toAddress);
                helper.setTo(toAddress);
                helper.setFrom(getFromAddress());

                String[] ccs = getCc();
                List lCc = new ArrayList();
                for (int i = 0; i < ccs.length; i++) {
                    //add configurated cc addresses to list
                    String CcElement = ccs[i];
                    lCc.add(CcElement);// w  w  w . jav  a2s. c  o  m
                }
                lCc.add(webRequest.getCon_e_mail());
                List ccCentre = wr.ccArchiveMailAddresses("" + webRequest.getStr_id_str(), "strains");

                Object[] o = null;
                Iterator it = ccCentre.iterator();
                while (it.hasNext()) {
                    o = (Object[]) it.next();
                    lCc.add(o[1].toString());
                }
                String[] ar = new String[lCc.size()];
                for (int i = 0; i < lCc.size(); i++) {
                    Object oo = lCc.get(i);
                    ar[i] = oo.toString();
                    System.out.println(oo.toString());
                }

                String[] bccs = getBcc();
                //msg.
                helper.setBcc(bccs);

                //msg.
                helper.setCc(ar);

                /*  format date string */
                String date = webRequest.getTimestamp().toString();
                String yyyy = date.substring(0, 4);
                String MM = date.substring(5, 7);
                String dd = date.substring(8, 10);

                date = dd + "-" + MM + "-" + yyyy;
                model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname());
                model.put("emmaid", webRequest.getStrain_id().toString());
                model.put("strainname", webRequest.getStrain_name());
                model.put("timestamp", date);
                model.put("sci_title", webRequest.getSci_title());
                model.put("sci_firstname", webRequest.getSci_firstname());
                model.put("sci_surname", webRequest.getSci_surname());
                model.put("sci_e_mail", webRequest.getSci_e_mail());
                model.put("strain_id", webRequest.getStrain_id());
                model.put("strain_name", webRequest.getStrain_name());
                model.put("common_name_s", webRequest.getCommon_name_s());
                model.put("req_material", webRequest.getReq_material());
                //new mta file inclusion
                model.put("requestID", webRequest.getId_req());
                model.put("BASEURL", BASEURL);
                StrainsManager sm = new StrainsManager();
                StrainsDAO sd = sm.getStrainByID(webRequest.getStr_id_str());
                if (!webRequest.getLab_id_labo().equals("4")) {
                    /*
                     * FOR LEGAL REASONS MTA FILE AND USAGE TEXT SHOULD NOT BE SHOWN FOR MRC STOCK.
                     * MRC WILL SEND MTA SEPARATELY (M.FRAY EMMA IT MEETING 28-29 OCT 2010)
                     */
                    model.put("mtaFile", sd.getMta_file());
                }
                //########################################################            

                String rtoolsID = "";
                List rtools = wr.strainRToolID(webRequest.getStr_id_str());
                it = rtools.iterator();
                while (it.hasNext()) {
                    Object oo = it.next();
                    rtoolsID = oo.toString();
                }

                model.put("rtoolsID", rtoolsID);
                //TEMPLATE SELECTION

                if (panelDecision.equals("yes")) {
                    //we need to send a mail
                    if (webRequest.getApplication_type().contains("ta_")) {
                        System.out.println(getTemplatePath() + getTaOrRequestYesTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOrRequestYesTemplate(), model);
                    }
                }
                /* webRequest.getTa_panel_decision().equals("no") */
                if (panelDecision.equals("no")) {
                    System.out.println("panel decision == no ==");
                    if (applicationType.equals("ta_or_request")) {
                        System.out.println("path to template for ta_or_req and no==" + getTemplatePath()
                                + getTaOrRequestNoTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOrRequestNoTemplate(), model);
                    }
                    if (applicationType.equals("ta_only")) {
                        //TODO IF NO AND TA_ONLY THEN REQ_STATUS=CANC
                        webRequest.setReq_status("CANC");
                        System.out.println("path to template for ta_only and no==" + getTemplatePath()
                                + getTaOnlyNoTemplate());
                        content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                                getTemplatePath() + getTaOnlyNoTemplate(), model);
                    }
                }

                //send message
                //msg.
                helper.setSubject(
                        msgSubject + webRequest.getStrain_name() + "(" + webRequest.getStrain_id() + ")");
                //msg.
                helper.setText(content);

                //###/add mta file if associated with strain id
                String mtaFile = "";
                mtaFile = (new StringBuilder()).append(mtaFile).append(sd.getMta_file()).toString();

                if (mtaFile != null || model.get("mtaFile").toString().equals("")) {
                    FileSystemResource fileMTA = new FileSystemResource(new File(getPathToMTA() + mtaFile));
                    //need to check for a valid mta filename use period extension separator, all mtas are either .doc or .pdf
                    if (fileMTA.exists() && fileMTA.toString().contains(".")) {
                        //M Hagn decided now to not send an MTA at this point as users should have already received one. Was confusing users to receive another philw@ebi.ac.uk 05042011
                        //helper.addAttachment(model.get("mtaFile").toString(), fileMTA);
                    }
                }
                System.out.println("Rtools=" + model.get("rtoolsID") + " and labID=" + model.get("labID"));
                if (request.getParameter("TEST") != null) {
                    // TESTER SUBMITTED EMAIL ADDRESS
                    //msg.
                    helper.setTo(request.getParameter("TEST"));
                    //msg.
                    helper.setCc(request.getParameter("TEST"));
                    String Ccs = "";
                    for (int i = 0; i < ar.length; i++) {
                        Ccs = Ccs + ", " + ar[i];
                    }
                    //msg.
                    helper.setText("TEST EMAIL, LIVE EMAIL SENT TO " + toAddress + " CC'D TO :\n\n " + Ccs
                            + " LIVE MESSAGE TEXT FOLLOWS BELOW::\n\n" + content);
                }
                if (!toAddress.equals("")) {
                    //Set notes to contain ta mail sent trigger
                    String notes = webRequest.getNotes();
                    notes = notes + "TA mail sent";
                    webRequest.setNotes(notes);
                }
                getJavaMailSender().send(msg);
            }
        }
    }

    if (request.getParameter("fSourceID") != null || !request.getParameter("fSourceID").equals("")) {
        //save requestfunding source ID
        boolean saveOnly = false;
        int sour_id = Integer.parseInt(request.getParameter("fSourceID"));
        int srcID = Integer.parseInt(webRequest.getId_req());
        System.out.println("fSourceID==" + srcID);
        srd = wr.getReqSourcesByID(srcID);//sm.getSourcesByID(srcID);

        //  
        try {
            srd.getSour_id();//ssd.getSour_id();
            srd.setSour_id(sour_id);
        } catch (NullPointerException np) {
            srd = new Sources_RequestsDAO();
            int reqID = Integer.parseInt(webRequest.getId_req());

            srd.setReq_id_req(reqID);

            srd.setSour_id(sour_id);
            //save only here not save or update
            saveOnly = true;

        }

        if (saveOnly) {
            wr.saveOnly(srd);
            System.out.println("THIS IS NOW SAVED:: SAVEONLY");
        } else if (!saveOnly) {
            //save or update
            System.out.println("SAVEORUPDATEONLY + value is.." + srd);
            wr.save(srd);
            System.out.println("THIS IS NOW SAVED:: SAVEORUPDATEONLY");
        }

    }

    wr.saveRequest(webRequest);
    request.getSession().setAttribute("message",
            getMessageSourceAccessor().getMessage("Message", "Your update submitted successfully"));

    if (webRequest.getProjectID().equals("3") && webRequest.getLab_id_labo().equals("1961")) {
        //OK this is a Sanger/Eucomm strain and could be subject to charging so may need to send xml
        if (request.getParameter("currentReqStatus").contains("PR")
                && webRequest.getReq_status().equals("SHIP")) {

            //status changed to shipped from a non cancelled request so subject to a charge
            model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname());
            model.put("emmaid", webRequest.getStrain_id().toString());
            model.put("strainname", webRequest.getStrain_name());
            model.put("timestamp", webRequest.getTimestamp());
            model.put("ftimestamp", webRequest.getFtimestamp());
            model.put("sci_title", webRequest.getSci_title());
            model.put("sci_firstname", webRequest.getSci_firstname());
            model.put("sci_surname", webRequest.getSci_surname());
            model.put("sci_e_mail", webRequest.getSci_e_mail());
            model.put("sci_phone", webRequest.getSci_phone());
            model.put("sci_fax", webRequest.getSci_fax());
            model.put("con_title", webRequest.getCon_title());
            model.put("con_firstname", webRequest.getCon_firstname());
            model.put("con_surname", webRequest.getCon_surname());
            model.put("con_e_mail", webRequest.getCon_e_mail());
            model.put("con_phone", webRequest.getCon_phone());
            model.put("con_fax", webRequest.getCon_fax());
            model.put("con_institution", webRequest.getCon_institution());
            model.put("con_dept", webRequest.getCon_dept());
            model.put("con_addr_1", webRequest.getCon_addr_1());
            model.put("con_addr_2", webRequest.getCon_addr_2());
            model.put("con_province", webRequest.getCon_province());
            model.put("con_town", webRequest.getCon_town());
            model.put("con_postcode", webRequest.getCon_postcode());
            model.put("con_country", webRequest.getCon_country());

            //billing details

            if (!webRequest.getRegister_interest().equals("1")) {
                model.put("PO_ref", webRequest.getPO_ref());
                model.put("bil_title", webRequest.getBil_title());
                model.put("bil_firstname", webRequest.getBil_firstname());
                model.put("bil_surname", webRequest.getBil_surname());
                model.put("bil_e_mail", webRequest.getBil_e_mail());
                model.put("bil_phone", webRequest.getBil_phone());
                model.put("bil_fax", webRequest.getBil_fax());
                model.put("bil_institution", webRequest.getBil_institution());
                model.put("bil_dept", webRequest.getBil_dept());
                model.put("bil_addr_1", webRequest.getBil_addr_1());
                model.put("bil_addr_2", webRequest.getBil_addr_2());
                model.put("bil_province", webRequest.getBil_province());
                model.put("bil_town", webRequest.getBil_town());
                model.put("bil_postcode", webRequest.getBil_postcode());
                model.put("bil_country", webRequest.getBil_country());
                model.put("bil_vat", webRequest.getBil_vat());
            }
            //end biling details

            model.put("strain_id", webRequest.getStrain_id());
            model.put("strain_name", escapeXml(webRequest.getStrain_name()));
            model.put("common_name_s", webRequest.getCommon_name_s());
            model.put("req_material", webRequest.getReq_material());
            model.put("live_animals", webRequest.getLive_animals());
            model.put("frozen_emb", webRequest.getFrozen_emb());
            model.put("frozen_spe", webRequest.getFrozen_spe());
            // TA application details
            model.put("application_type", webRequest.getApplication_type());
            model.put("ta_eligible", webRequest.getEligible_country());

            if (webRequest.getApplication_type().contains("ta")) {
                model.put("ta_proj_desc", webRequest.getProject_description());
                model.put("ta_panel_sub_date", webRequest.getTa_panel_sub_date());
                model.put("ta_panel_decision_date", webRequest.getTa_panel_decision_date());
                model.put("ta_panel_decision", webRequest.getTa_panel_decision());
            } else {
                model.put("ta_proj_desc", "");
                model.put("ta_panel_sub_date", "");
                model.put("ta_panel_decision_date", "");
                model.put("ta_panel_decision", "");
            }
            model.put("ROI", webRequest.getRegister_interest());

            model.put("europhenome", webRequest.getEurophenome());
            model.put("wtsi_mouse_portal", webRequest.getWtsi_mouse_portal());

            //now create xml file

            String xmlFileContent = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                    "org/emmanet/util/velocitytemplates/requestXml-Template.vm", model);

            File file = new File(Configuration.get("sangerLineDistribution"));
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
            out.write(xmlFileContent);
            out.close();

            //email file now
            MimeMessage message = getJavaMailSender().createMimeMessage();

            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setReplyTo("emma@infrafrontier.eu");
                helper.setFrom("emma@infrafrontier.eu");
                helper.setBcc(bcc);
                helper.setTo(sangerLineDistEmail);
                helper.setSubject("Sanger Line Distribution " + webRequest.getStrain_id());
                helper.addAttachment("sangerlinedistribution.xml", file);
                getJavaMailSender().send(message);
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
        }
    }
    System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL"));
    return new ModelAndView(
            "redirect:requestsUpdateInterface.emma?Edit=" + request.getParameter("Edit").toString()
                    + "&strainID=" + request.getParameter("strainID").toString() + "&archID="
                    + request.getParameter("archID").toString());
}