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:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Sends the notification by email./*from ww  w .  j  av a  2s  .c o m*/
 * <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:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

public void sendMailNotification(ReportExecutionJob job, ReportJob jobDetails, List reportOutputs)
        throws JobExecutionException {
    ReportJobMailNotification mailNotification = jobDetails.getMailNotification();

    if (mailNotification != null) {
        try {//from  ww  w  .  j  av  a2 s  . c o m
            // skip mail notification when job fails
            if (mailNotification.isSkipNotificationWhenJobFails() && (!job.exceptions.isEmpty())) {
                return;
            }
            JavaMailSender mailSender = job.getMailSender();
            String fromAddress = job.getFromAddress();
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, job.getCharacterEncoding());
            messageHelper.setFrom(fromAddress);
            messageHelper.setSubject(mailNotification.getSubject());

            StringBuffer messageText = new StringBuffer();
            addMailRecipients(mailNotification, messageHelper);

            boolean isEmailBodyOccupied = false;

            if (reportOutputs != null && !reportOutputs.isEmpty()) {
                byte resultSendType = jobDetails.getMailNotification().getResultSendType();

                if ((resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED)
                        || (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED_ZIP_ALL_OTHERS)) {
                    List attachmentReportList = new ArrayList();
                    for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
                        ReportOutput output = (ReportOutput) it.next();
                        if ((!isEmailBodyOccupied) && output.getFileType().equals(ContentResource.TYPE_HTML)
                                && (job.exceptions.isEmpty())) {
                            // only embed html output
                            embedOutput(messageHelper, output);
                            isEmailBodyOccupied = true;
                        } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_EMBED) {
                            // save the rest of the output as attachments
                            attachOutput(job, messageHelper, output,
                                    (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT));
                        } else { // RESULT_SEND_EMBED_ZIP_ALL_OTHERS
                            attachmentReportList.add(output);
                        }
                    }
                    if (attachmentReportList.size() > 0) {
                        // put the rest of attachments in 1 zip file
                        attachOutputs(job, messageHelper, attachmentReportList);

                    }
                } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT
                        || resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_NOZIP) {
                    for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
                        ReportOutput output = (ReportOutput) it.next();
                        attachOutput(job, messageHelper, output,
                                (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT));
                    }
                } else if (resultSendType == ReportJobMailNotification.RESULT_SEND_ATTACHMENT_ZIP_ALL) {
                    // put all the attachments in 1 zip file
                    attachOutputs(job, messageHelper, reportOutputs);
                } else {
                    appendRepositoryLinks(job, messageText, reportOutputs);
                }
            }
            if (mailNotification.isIncludingStackTraceWhenJobFails()) {
                if (!job.exceptions.isEmpty()) {
                    for (Iterator it = job.exceptions.iterator(); it.hasNext();) {
                        ExceptionInfo exception = (ExceptionInfo) it.next();

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

                        attachException(messageHelper, exception);
                    }
                }
            }
            String text = mailNotification.getMessageText();
            if (!job.exceptions.isEmpty()) {
                if (mailNotification.getMessageTextWhenJobFails() != null)
                    text = mailNotification.getMessageTextWhenJobFails();
                else
                    text = job.getMessage("report.scheduling.job.default.mail.notification.message.on.fail",
                            null);
            }
            if (!isEmailBodyOccupied)
                messageHelper.setText(text + "\n" + messageText.toString());
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("Error while sending report job result mail", e);
            throw new JSExceptionWrapper(e);
        }
    }
}

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 {//ww  w.  j a v a2 s  .  c om
        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.imap.ImapMessageTest.java

public void testEncodedFromToAddresses() throws Exception {
    // RFC1342//  www.java  2s  . c o  m
    String addressString = "ars.kov@gmail.com";
    String personalString = "?? ";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");

    // Following method returns the address with quoted personal aka <["?? "] <ars.kov@gmail.com>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // So, just using decode, for now
    String decodedAddress = MimeUtility.decodeText(address.toString());

    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded",
            decodedAddress.equals(InternetAddress.toString(new Address[] { address })));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");

    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);

    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);

    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());

    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);

    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}

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);//from  www  .  j a v  a2  s  .  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());
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)//from   www  .j a va  2  s. c  om
public boolean sendMessage(@NotNull final Message message)
        throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException {

    LOGGER.info("BEGIN : sendMessage()");
    LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString());

    try {
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

        // process FROM addresses
        InternetAddress from;
        String appName = configService.getByName("app_title").getValue();

        //We used the configured outbound email address for every outgoing message
        //If a message was initiated by an end user, their name will be attached to the 'from' while
        //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>"
        String name = appName + " Administrator";
        if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty()
                && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) {
            InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId());
            if (froms.length > 0) {
                name = message.getSender().getFullName() + " (" + appName + ")";
            }
        }

        from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name);
        if (!this.validateEmail(from.getAddress())) {
            throw new AddressException("Invalid from: email address [" + from.getAddress() + "]");
        }

        mimeMessageHelper.setFrom(from);
        message.setSentFromAddress(from.toString());
        mimeMessageHelper.setReplyTo(from);
        message.setSentReplyToAddress(from.toString());

        // process TO addresses
        InternetAddress[] tos = null;
        if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams         
            tos = getEmailAddresses(message.getRecipient(), "to:", message.getId());
        } else {
            tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId());
        }
        if (tos.length > 0) {
            mimeMessageHelper.setTo(tos);
            message.setSentToAddresses(StringUtils.join(tos, ",").trim());
        } else {
            StringBuilder errorMsg = new StringBuilder();

            errorMsg.append(addMessageIdToError(message) + " Message " + message.toString()
                    + " could not be sent. No valid recipient email address found: '");

            if (message.getRecipient() != null) {
                errorMsg.append(message.getRecipient().getPrimaryEmailAddress());
            } else {
                errorMsg.append(message.getRecipientEmailAddress());
            }
            LOGGER.error(errorMsg.toString());
            throw new MessagingException(errorMsg.toString());
        }

        // process BCC addresses
        try {
            InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId());
            if (bccs.length > 0) {
                mimeMessageHelper.setBcc(bccs);
                message.setSentBccAddresses(StringUtils.join(bccs, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        // process CC addresses
        try {
            InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId());
            if (carbonCopies.length > 0) {
                mimeMessageHelper.setCc(carbonCopies);
                message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        mimeMessageHelper.setSubject(message.getSubject());
        mimeMessageHelper.setText(message.getBody());
        mimeMessage.setContent(message.getBody(), "text/html");

        send(mimeMessage);

        message.setSentDate(new Date());
        messageDao.save(message);
    } catch (final MessagingException e) {
        LOGGER.error("ERROR : sendMessage() : {}", e);
        handleSendMessageError(message);
        throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e);
    }

    LOGGER.info("END : sendMessage()");
    return true;
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {//www.j  ava 2 s  .c  om
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getReportSmtpServer());
        javaMailSenderImpl.setPort(this.getRerportSmtpPort());
        javaMailSenderImpl.setUsername(this.getReportSmtpUsername());
        javaMailSenderImpl.setPassword(this.getReportSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setFrom(this.getReportSmtpFromAddress());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}

From source file:org.openvpms.web.component.error.ErrorReporter.java

/**
 * Reports an error./*from   www  .jav  a 2 s. co  m*/
 *
 * @param report  the error report
 * @param replyTo the reply-to email address. May be {@code null}
 */
public void report(final ErrorReport report, String replyTo) {
    try {
        JavaMailSender sender = ServiceHelper.getMailSender();
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String subject = report.getVersion() + ": " + report.getMessage();
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setTo(to);
        if (!StringUtils.isEmpty(replyTo)) {
            helper.setReplyTo(replyTo);
        }
        String text = getText(report);
        if (text != null) {
            helper.setText(text);
        }
        InputStreamSource source = new InputStreamSource() {
            public InputStream getInputStream() {
                return new ByteArrayInputStream(report.toXML().getBytes());
            }
        };
        helper.addAttachment("error-report.xml", source, DocFormats.XML_TYPE);
        sender.send(message);
    } catch (Throwable exception) {
        log.error(exception, exception);
        ErrorDialog.show(Messages.get("errorreportdialog.senderror"));
    }
}

From source file:org.openvpms.web.component.mail.AbstractMailer.java

/**
 * Populates the mail message./*from   ww  w  . j  a v a2 s .  co m*/
 *
 * @param helper the message helper
 * @throws MessagingException           for any messaging error
 * @throws UnsupportedEncodingException if the character encoding is not supported
 */
protected void populateMessage(MimeMessageHelper helper)
        throws MessagingException, UnsupportedEncodingException {
    helper.setFrom(getFrom());
    String[] to = getTo();
    if (to != null && to.length != 0) {
        helper.setTo(to);
    }
    String[] cc = getCc();
    if (cc != null && cc.length != 0) {
        helper.setCc(cc);
    }
    String[] bcc = getBcc();
    if (bcc != null && bcc.length != 0) {
        helper.setBcc(bcc);
    }
    helper.setSubject(getSubject());
    if (body != null) {
        helper.setText(body);

    } else {
        helper.setText("");
    }
    for (Document attachment : attachments) {
        addAttachment(helper, attachment);
    }
}

From source file:org.openvpms.web.workspace.reporting.reminder.ReminderEmailProcessor.java

/**
 * Processes a list of reminder events.//from  w ww  . j a v  a 2s.co  m
 *
 * @param events           the events
 * @param shortName        the report archetype short name, used to select the document template if none specified
 * @param documentTemplate the document template to use. May be {@code null}
 */
protected void process(List<ReminderEvent> events, String shortName, DocumentTemplate documentTemplate) {
    ReminderEvent event = events.get(0);
    Contact contact = event.getContact();
    DocumentTemplateLocator locator = new ContextDocumentTemplateLocator(documentTemplate, shortName,
            getContext());
    documentTemplate = locator.getTemplate();
    if (documentTemplate == null) {
        throw new ReportingException(ReminderMissingDocTemplate);
    }

    try {
        EmailAddress from = addresses.getAddress(event.getCustomer());
        IMObjectBean bean = new IMObjectBean(contact);
        String to = bean.getString("emailAddress");

        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setValidateAddresses(true);
        helper.setFrom(from.getAddress(), from.getName());
        helper.setTo(to);

        String subject = documentTemplate.getEmailSubject();
        if (StringUtils.isEmpty(subject)) {
            subject = documentTemplate.getName();
        }
        String body = documentTemplate.getEmailText();
        if (StringUtils.isEmpty(body)) {
            throw new ReportingException(TemplateMissingEmailText, documentTemplate.getName());
        }
        helper.setText(body);

        final Document reminder = createReport(events, documentTemplate);
        final DocumentHandler handler = handlers.get(reminder.getName(),
                reminder.getArchetypeId().getShortName(), reminder.getMimeType());

        helper.setSubject(subject);
        helper.addAttachment(reminder.getName(), new InputStreamSource() {
            public InputStream getInputStream() {
                return handler.getContent(reminder);
            }
        });
        sender.send(message);
    } catch (ArchetypeServiceException exception) {
        throw exception;
    } catch (ReminderProcessorException exception) {
        throw exception;
    } catch (ReportingException exception) {
        throw exception;
    } catch (Throwable exception) {
        throw new ReportingException(FailedToProcessReminder, exception, exception.getMessage());
    }
}