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

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

Introduction

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

Prototype

public void setText(String text) throws MessagingException 

Source Link

Document

Set the given text directly as content in non-multipart mode or as default body part in multipart mode.

Usage

From source file:business.services.MailService.java

@Transactional
public void notifyScientificCouncil(@NotNull RequestRepresentation request) {
    log.info("Notify scientic council for request " + request.getProcessInstanceId() + ".");

    List<User> members = userService.findScientificCouncilMembers();
    for (User member : members) {
        log.info("Sending notification to user " + member.getUsername());
        try {/*from   www .java2s. c o  m*/
            MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
            message.setTo(member.getContactData().getEmail());
            message.setFrom(getFrom(), fromName);
            message.setReplyTo(replyAddress, replyName);
            message.setSubject(String.format("Nieuwe PALGA-aanvraag aan u voorgelegd, aanvraagnummer: %s",
                    request.getRequestNumber()));
            String requestLink = getLink("/#/request/view/" + request.getProcessInstanceId());
            message.setText(String.format(scientificCouncilNotificationTemplate, requestLink));
            mailSender.send(message.getMimeMessage());
        } catch (MessagingException e) {
            log.error(e.getMessage());
            throw new EmailError("Email error: " + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
            throw new EmailError("Email error: " + e.getMessage());
        }
    }
}

From source file:uk.ac.gda.dls.client.feedback.FeedbackDialog.java

@Override
protected void createButtonsForButtonBar(Composite parent) {

    GridData data = new GridData(SWT.FILL, SWT.FILL, false, true, 4, 1);
    GridLayout layout = new GridLayout(5, false);
    parent.setLayoutData(data);/*from   w w w  .  ja va 2 s  .c o m*/
    parent.setLayout(layout);

    Button attachButton = new Button(parent, SWT.TOGGLE);
    attachButton.setText("Attach File(s)");
    attachButton.setToolTipText("Add files to feedback");

    final Button screenGrabButton = new Button(parent, SWT.CHECK);
    screenGrabButton.setText("Include Screenshot");
    screenGrabButton.setToolTipText("Send screenshot with feedback");

    Label space = new Label(parent, SWT.NONE);
    space.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

    Button sendButton = new Button(parent, SWT.PUSH);
    sendButton.setText("Send");

    Button cancelButton = new Button(parent, SWT.PUSH);
    cancelButton.setText("Cancel");

    sendButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {

            final String name = nameText.getText();
            final String email = emailText.getText();
            final String subject = subjectText.getText();
            final String description = descriptionText.getText();

            fileList = attachedFileList.getItems();

            Job job = new Job("Send feedback email") {
                @Override
                protected IStatus run(IProgressMonitor monitor) {

                    try {
                        final String recipientsProperty = LocalProperties.get("gda.feedback.recipients",
                                "dag-group@diamond.ac.uk");
                        final String[] recipients = recipientsProperty.split(" ");
                        for (int i = 0; i < recipients.length; i++) {
                            recipients[i] = recipients[i].trim();
                        }

                        final String from = String.format("%s <%s>", name, email);

                        final String beamlineName = LocalProperties.get("gda.beamline.name",
                                "Beamline Unknown");
                        final String mailSubject = String.format("[GDA feedback - %s] %s",
                                beamlineName.toUpperCase(), subject);

                        final String smtpHost = LocalProperties.get("gda.feedback.smtp.host", "localhost");

                        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
                        mailSender.setHost(smtpHost);

                        MimeMessage message = mailSender.createMimeMessage();
                        final MimeMessageHelper helper = new MimeMessageHelper(message,
                                (FeedbackDialog.this.hasFiles && fileList.length > 0)
                                        || FeedbackDialog.this.screenshot);
                        helper.setFrom(from);
                        helper.setTo(recipients);
                        helper.setSubject(mailSubject);
                        helper.setText(description);

                        if (FeedbackDialog.this.screenshot) {
                            PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                                @Override
                                public void run() {
                                    String fileName = "/tmp/feedbackScreenshot.png";
                                    try {
                                        captureScreen(fileName);
                                        FileSystemResource file = new FileSystemResource(new File(fileName));
                                        helper.addAttachment(file.getFilename(), file);
                                    } catch (Exception e) {
                                        logger.error("Could not attach screenshot to feedback", e);
                                    }
                                }
                            });
                        }

                        if (FeedbackDialog.this.hasFiles) {
                            for (String fileName : fileList) {
                                FileSystemResource file = new FileSystemResource(new File(fileName));
                                helper.addAttachment(file.getFilename(), file);
                            }
                        }

                        {//required to workaround class loader issue with "no object DCH..." error
                            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                            mc.addMailcap(
                                    "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                            mc.addMailcap(
                                    "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                            CommandMap.setDefaultCommandMap(mc);
                        }
                        mailSender.send(message);
                        return Status.OK_STATUS;
                    } catch (Exception ex) {
                        logger.error("Could not send feedback", ex);
                        return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 1, "Error sending email", ex);
                    }

                }
            };

            job.schedule();

            setReturnCode(OK);
            close();
        }
    });

    cancelButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            setReturnCode(CANCEL);
            close();
        }
    });

    attachButton.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            hasFiles = !hasFiles;
            GridData data = ((GridData) attachments.getLayoutData());
            data.exclude = !hasFiles;
            attachments.setVisible(hasFiles);
            topParent.layout();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });

    screenGrabButton.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            screenshot = ((Button) e.widget).getSelection();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
}

From source file:com.indicator_engine.controller.RegistrationController.java

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String processRegistrationForm(@Valid @ModelAttribute("RegisterForm") RegistrationForm RegisterForm,
        BindingResult bindingResult, Map<String, Object> model) {
    if (bindingResult.hasErrors()) {
        return "app/register";
    }/*from   w ww .  j a  v a2 s.c  o m*/
    UserCredentialsDao userDetailsBean = (UserCredentialsDao) appContext.getBean("userDetails");
    MimeMessage message = mailSender.createMimeMessage();
    String errorMsg;
    String uname = RegisterForm.getUserName();
    String password = RegisterForm.getPassword();
    String hashedPassword = encoder.encode(password);
    Date dob = RegisterForm.getDob();
    java.sql.Date sqlStartDate = null;
    sqlStartDate = new java.sql.Date(dob.getTime());
    String email = RegisterForm.getEmail();
    // Error Handling Not done Yet. Synchronize Java Script checks + Server Side checks. Eliminate redundant checks
    if (uname == null || email == null || password == null)
        errorMsg = "Error : Please Check your ";
    UserCredentials uc = new UserCredentials(uname, hashedPassword,
            new UserProfile(" ", " ", sqlStartDate, 0, " ", " ", " ", 0, " ", email));
    userDetailsBean.add(uc);
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("goalla@rwth-aachen.de");
        helper.setTo(uc.getUp().getEmailid());
        helper.setSubject("One Time Password for Verification");

        /*Map<String, Object> modelMsg = new HashMap<String, Object>();
        model.put("UserName", uc.getUname());
        model.put("EmailID", uc.getUp().getEmailid());
        model.put("DOB", uc.getUp().getDob());
        model.put("OTP", uc.getOtp());
        String emailText = VelocityEngineUtils.mergeTemplateIntoString(
            velocityEngine, "registrationEmailTemplate.vm", "UTF-8", modelMsg); */

        helper.setText("OTP For Verification :  " + uc.getOtp());
        /*FileSystemResource couponImage =
           new FileSystemResource("logo.png");
        helper.addAttachment("logo.png", logoImage);
        ClassPathResource image = new ClassPathResource("rwth.png");
        helper.addInline("UniLogo", image); */
    } catch (javax.mail.MessagingException ex) {
    }
    mailSender.send(message);
    model.put("msg", uc.getUid());
    return "app/registration_success";
}

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   w  ww. j av a 2 s  . c  om
        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:eu.openanalytics.shinyproxy.controllers.IssueController.java

public void sendSupportMail(IssueForm form, Proxy proxy) {
    String supportAddress = getSupportAddress();
    if (supportAddress == null)
        throw new RuntimeException("Cannot send mail: no support address configured");
    if (mailSender == null)
        throw new RuntimeException("Cannot send mail: no smtp settings configured");

    try {//from w ww  .  j  a v a2 s.  co  m
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        // Headers
        helper.setFrom(environment.getProperty("proxy.support.mail-from-address", "issues@shinyproxy.io"));
        helper.addTo(supportAddress);
        helper.setSubject("ShinyProxy Error Report");

        // Body
        StringBuilder body = new StringBuilder();
        String lineSep = System.getProperty("line.separator");
        body.append(String.format("This is an error report generated by ShinyProxy%s", lineSep));
        body.append(String.format("User: %s%s", form.userName, lineSep));
        if (form.appName != null)
            body.append(String.format("App: %s%s", form.appName, lineSep));
        if (form.currentLocation != null)
            body.append(String.format("Location: %s%s", form.currentLocation, lineSep));
        if (form.customMessage != null)
            body.append(String.format("Message: %s%s", form.customMessage, lineSep));
        helper.setText(body.toString());

        // Attachments (only if container-logging is enabled)
        if (logService.isLoggingEnabled() && proxy != null) {
            Path[] filePaths = logService.getLogFiles(proxy);
            for (Path p : filePaths) {
                if (Files.exists(p))
                    helper.addAttachment(p.toFile().getName(), p.toFile());
            }
        }

        mailSender.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Failed to send email", e);
    }
}

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());//  w w  w.  java 2s.com

    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 = "/edit", method = RequestMethod.POST)
public ModelAndView editApp(ModelMap model, Authentication authentication,
        @ModelAttribute("application") Application application, MultipartFile icon,
        @RequestParam(value = "certificate", required = false) MultipartFile certificate,
        BindingResult result) {//ww  w .  ja va2 s.co m
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());
    List<Permission> permissions = permissionServices.getAllPermissions();

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());

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

        applicationValidator.validate(application, result);

        log.info("app id: " + application.getId());
        Application dbApp = appManagement.getApplication(application.getId());

        if (!user.getUsername().equals(dbApp.getDeveloper().getResidentIdentificationNumber())) {
            throw new IllegalArgumentException(
                    "The application developer is not the same as the logged in user");
        }

        if (application.getIcon() == null && dbApp.getIcon() != null && dbApp.getIcon().length > 0) {
            application.setIcon(dbApp.getIcon());
            log.debug("Icon wasn't updated this time around");
        } else if (application.getIcon() != null) {
            log.debug("Icon was updated");
            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");
            }
        }

        application.setCertificates(dbApp.getCertificates());
        application.setRegistrationDate(dbApp.getRegistrationDate());
        application.setState(dbApp.getState());
        application.setDeveloper(developer);

        //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));
        }

        //Error handling
        if (result.hasErrors()) {
            model.addAttribute(application);
            model.addAttribute("scopes", permissions);
            return new ModelAndView("application/edit");
        }

        Application savedApp = appManagement.updateApplication(application);

        //Remove everything old.
        // Just allow one certificate to be set right now even though the model allows for more.
        //If this behavior is unwanted the GUI has to adapt for this as well as it only caters
        //for on certificate right now.
        if (certificate != null && certificate.getSize() > 0) {
            Set<Certificate> oldCerts = new HashSet<>();

            //Clone in order to not get a concurrent modification exception
            for (Certificate cert : savedApp.getCertificates()) {
                oldCerts.add(cert);
            }

            //Remove anything old
            for (Certificate cert : oldCerts) {
                cert.setApplication(null);
                savedApp.getCertificates().remove(cert);
                appManagement.removeCertificate(cert);
            }

            //Set the new Certificate
            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 new ModelAndView("redirect:/developer");
}

From source file:business.services.MailService.java

public void notifyLab(@NotNull LabRequestRepresentation labRequest) {
    log.info("Notify lab for lab request " + labRequest.getId() + ".");

    Lab lab = labRequest.getLab();// ww  w  .j a  v  a2  s  . c  o  m
    if (lab.getEmailAddresses() == null || lab.getEmailAddresses().isEmpty()) {
        log.warn("No email address set for lab " + lab.getNumber());
        return;
    }
    String recipients = String.join(", ", lab.getEmailAddresses());
    log.info("Sending notification to " + recipients);
    try {
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        for (String email : lab.getEmailAddresses()) {
            message.addTo(email);
        }
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(String.format("PALGA-verzoek aan laboratorium, aanvraagnummer: %s",
                labRequest.getLabRequestCode()));
        String labRequestLink = getLink("/#/lab-request/view/" + labRequest.getId());
        String body = String.format(labNotificationTemplate, labRequestLink, // %1
                labRequest.getLabRequestCode(), // %2
                labRequest.getRequest().getTitle(), // %3
                labRequest.getRequesterName(), // %4
                labRequest.getRequest().getPathologistName() == null ? ""
                        : labRequest.getRequest().getPathologistName(), // %5
                labRequest.getRequesterLab().getName() // %6
        );
        message.setText(body);
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessage.java

@Override
public MimeMessage apply(final Email email) {
    final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
            fromNullable(email.getEncoding()).or(Charset.forName("UTF-8")).displayName());

    try {/*from  w  w w . ja va  2s.c  o m*/
        messageHelper.setFrom(email.getFrom());
        if (ofNullable(email.getReplyTo()).isPresent()) {
            messageHelper.setReplyTo(email.getReplyTo());
        }
        if (ofNullable(email.getTo()).isPresent()) {
            for (final InternetAddress address : email.getTo()) {
                messageHelper.addTo(address);
            }
        }
        if (ofNullable(email.getCc()).isPresent()) {
            for (final InternetAddress address : email.getCc()) {
                messageHelper.addCc(address);
            }
        }
        if (ofNullable(email.getBcc()).isPresent()) {
            for (final InternetAddress address : email.getBcc()) {
                messageHelper.addBcc(address);
            }
        }
        if (ofNullable(email.getAttachments()).isPresent()) {
            for (final EmailAttachmentImpl attachment : email.getAttachments()) {
                try {
                    messageHelper.addAttachment(attachment.getAttachmentName(), attachment.getInputStream(),
                            attachment.getContentType().getType());
                } catch (IOException e) {
                    log.error("Error while converting Email to MimeMessage");
                    throw new EmailConversionException(e);
                }
            }
        }
        messageHelper.setSubject(ofNullable(email.getSubject()).orElse(""));
        messageHelper.setText(ofNullable(email.getBody()).orElse(""));

        if (nonNull(email.getSentAt())) {
            messageHelper.setSentDate(email.getSentAt());
        }
    } catch (MessagingException e) {
        log.error("Error while converting Email to MimeMessage");
        throw new EmailConversionException(e);
    }

    return mimeMessage;
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobAlertImpl.java

public void sendAlertMail(Job job, ReportJob jobDetails, List<ExceptionInfo> exceptions,
        JavaMailSender mailSender, String fromAddress, String[] toAddresses, String characterEncoding)
        throws JobExecutionException {
    ReportJobAlert alert = jobDetails.getAlert();
    boolean isSucceed = exceptions.isEmpty();
    switch (alert.getJobState()) {
    case FAIL_ONLY:
        if (isSucceed)
            return;
        break;//from   w w w. j ava  2 s  . co m
    case SUCCESS_ONLY:
        if (!isSucceed)
            return;
        break;
    case NONE:
        return;
    }
    if (alert != null) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, characterEncoding);
            messageHelper.setFrom(fromAddress);
            String subject = alert.getSubject();
            if ((subject == null) && (job instanceof ReportExecutionJob))
                subject = ((ReportExecutionJob) job).getMessage("report.scheduling.job.default.alert.subject",
                        null);
            messageHelper.setSubject(subject);

            StringBuffer messageText = new StringBuffer();

            String text = (isSucceed ? alert.getMessageText() : alert.getMessageTextWhenJobFails());
            if (text != null) {
                messageText.append(text);
            }
            messageHelper.setTo(toAddresses);

            if (alert.isIncludingReportJobInfo()) {
                messageText.append("\n");
                messageText.append("ReportJob Info:").append("\n");
                messageText.append("Label = ").append(jobDetails.getLabel()).append("\n");
                messageText.append("ID = ").append(jobDetails.getId()).append("\n");
                messageText.append("Description = ").append(jobDetails.getDescription()).append("\n");
                messageText.append("Status = ").append(exceptions.isEmpty() ? "PASS" : "FAIL").append("\n");
            }

            if (alert.isIncludingStackTrace()) {
                if (!exceptions.isEmpty()) {
                    for (Iterator it = exceptions.iterator(); it.hasNext();) {
                        ExceptionInfo exception = (ExceptionInfo) it.next();

                        messageText.append("\n");
                        messageText.append(exception.getMessage());

                        attachException(messageHelper, exception);
                    }
                }
            }
            messageHelper.setText(messageText.toString());
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("Error while sending report job alert notification", e);
            throw new JSExceptionWrapper(e);
        }
    }
}