Example usage for org.springframework.mail.javamail JavaMailSender send

List of usage examples for org.springframework.mail.javamail JavaMailSender send

Introduction

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

Prototype

void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException;

Source Link

Document

Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.

Usage

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 {//w w w  . j a  v  a 2 s  . c  om
            // 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:com.glaf.mail.MailSenderImpl.java

public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception {
    if (StringUtils.isEmpty(mailMessage.getMessageId())) {
        mailMessage.setMessageId(UUID32.getUUID());
    }/*w  w w  .  j  av  a 2 s.  c  o m*/

    mailHelper = new MxMailHelper();
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    if (StringUtils.isNotEmpty(mailMessage.getFrom())) {
        messageHelper.setFrom(mailMessage.getFrom());
        mailFrom = mailMessage.getFrom();
    } else {
        if (StringUtils.isEmpty(mailFrom)) {
            mailFrom = MailProperties.getString("mail.mailFrom");
        }
        messageHelper.setFrom(mailFrom);
    }

    logger.debug("mailFrom:" + mailFrom);

    if (mailMessage.getTo() != null) {
        messageHelper.setTo(mailMessage.getTo());
    }

    if (mailMessage.getCc() != null) {
        messageHelper.setCc(mailMessage.getCc());
    }

    if (mailMessage.getBcc() != null) {
        messageHelper.setBcc(mailMessage.getBcc());
    }

    if (mailMessage.getReplyTo() != null) {
        messageHelper.setReplyTo(mailMessage.getReplyTo());
    }

    String mailSubject = mailMessage.getSubject();
    if (mailSubject == null) {
        mailSubject = "";
    }

    if (mailSubject != null) {
        // mailSubject = MimeUtility.encodeText(new
        // String(mailSubject.getBytes(), encoding), encoding, "B");
        mailSubject = MimeUtility.encodeWord(mailSubject);
    }

    mimeMessage.setSubject(mailSubject);

    Map<String, Object> dataMap = mailMessage.getDataMap();
    if (dataMap == null) {
        dataMap = new java.util.HashMap<String, Object>();
    }

    String serviceUrl = SystemConfig.getServiceUrl();

    logger.debug("mailSubject:" + mailSubject);
    logger.debug("serviceUrl:" + serviceUrl);

    if (serviceUrl != null) {
        String loginUrl = serviceUrl + "/mx/login";
        String mainUrl = serviceUrl + "/mx/main";
        logger.debug("loginUrl:" + loginUrl);
        dataMap.put("loginUrl", loginUrl);
        dataMap.put("mainUrl", mainUrl);
    }

    mailMessage.setDataMap(dataMap);

    if (StringUtils.isEmpty(mailMessage.getContent())) {
        Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId());
        if (template != null) {
            String templateType = template.getTemplateType();
            logger.debug("templateType:" + templateType);
            // logger.debug("content:" + template.getContent());
            if (StringUtils.equals(templateType, "eml")) {
                if (template.getContent() != null) {
                    Mail m = mailHelper.getMail(template.getContent().getBytes());
                    String content = m.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        template.setContent(content);
                        try {
                            Writer writer = new StringWriter();
                            TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer);
                            String text = writer.toString();
                            writer.close();
                            writer = null;
                            mailMessage.setContent(text);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }
            } else {
                try {
                    String text = TemplateUtils.process(dataMap, template.getContent());
                    mailMessage.setContent(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    if (StringUtils.isNotEmpty(mailMessage.getContent())) {
        String text = mailMessage.getContent();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            String href = callbackUrl + "?messageId=" + mailMessage.getMessageId();
            text = mailHelper.embedCallbackScript(text, href);
            mailMessage.setContent(text);
            logger.debug(text);
            messageHelper.setText(text, true);
        }
        messageHelper.setText(text, true);
    }

    logger.debug("mail body:" + mailMessage.getContent());

    Collection<Object> files = mailMessage.getFiles();

    if (files != null && !files.isEmpty()) {
        Iterator<Object> iterator = files.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof java.io.File) {
                java.io.File file = (java.io.File) object;
                FileSystemResource resource = new FileSystemResource(file);
                String name = file.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, resource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataSource) {
                DataSource dataSource = (DataSource) object;
                String name = dataSource.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, dataSource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataFile) {
                DataFile dataFile = (DataFile) object;
                if (StringUtils.isNotEmpty(dataFile.getFilename())) {
                    String name = dataFile.getFilename();
                    name = MailTools.chineseStringToAscii(name);
                    InputStreamSource inputStreamSource = new MxMailInputSource(dataFile);
                    messageHelper.addAttachment(name, inputStreamSource);
                    logger.debug("add attachment:" + name);
                }
            }
        }
    }

    mimeMessage.setSentDate(new java.util.Date());

    javaMailSender.send(mimeMessage);

    logger.info("-----------------------------------------");
    logger.info("????");
    logger.info("-----------------------------------------");
}

From source file:nl.strohalm.cyclos.utils.MailHandler.java

private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to,
        final String body, final boolean isHTML, final boolean throwException) {
    if (to == null || StringUtils.isEmpty(to.getAddress())) {
        return;//from   ww  w.  j a v a  2s  .  c o m
    }
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final MailSettings mailSettings = settingsService.getMailSettings();
    final JavaMailSender mailSender = mailSettings.getMailSender();
    final MimeMessage message = mailSender.createMimeMessage();
    final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset());

    try {
        helper.setFrom(getSystemAddress());
        if (replyTo != null) {
            helper.setReplyTo(replyTo);
        }
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(body, isHTML);
        mailSender.send(message);
    } catch (final MessagingException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        // Store the current Exception
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    } catch (final MailException e) {
        if (throwException) {
            throw new MailSendingException(subject, e);
        }
        CurrentTransactionData.setMailError(new MailSendingException(subject, e));
    }
}

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 w  w. j a v a 2s. com*/
    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.kuali.kra.service.impl.KcEmailServiceImpl.java

public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject,
        Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage,
        List<EmailAttachment> attachments) {
    JavaMailSender sender = createSender();

    if (sender != null) {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {//from  w  ww  .  ja  va 2 s . c  o m
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (CollectionUtils.isNotEmpty(toAddresses)) {
                for (String toAddress : toAddresses) {
                    helper.addTo(toAddress);
                }
            }

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            helper.setText(body, htmlMessage);

            if (CollectionUtils.isNotEmpty(ccAddresses)) {
                for (String ccAddress : ccAddresses) {
                    helper.addCc(ccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(bccAddresses)) {
                for (String bccAddress : bccAddresses) {
                    helper.addBcc(bccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    helper.addAttachment(attachment.getFileName(),
                            new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                }
            }

            sender.send(message);
        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        } catch (Exception e) {
            LOG.error("Failed to send email.", e);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email sender, please check your configuration.");
    }
}

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

/**
 * Reports an error./*from   w w w. j ava2s.c o 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.oscarehr.renal.web.RenalAction.java

public ActionForward sendPatientLetterAsEmail(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    String demographicNo = request.getParameter("demographic_no");
    String error = "";
    boolean success = true;
    JSONObject json = new JSONObject();

    final Demographic d = demographicDao.getDemographic(demographicNo);

    if (d == null) {
        error = "Patient not found.";
        success = false;/*from  ww w  .  jav  a  2 s . c o  m*/
    }
    if (d.getEmail() == null || d.getEmail().length() == 0 || d.getEmail().indexOf("@") == -1) {
        error = "No valid email address found for patient.";
        success = false;
    }

    if (success) {

        try {
            String documentDir = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR", "");
            File f = new File(documentDir, "orn_patient_letter.txt");
            String template = IOUtils.toString(new FileInputStream(f));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            VelocityContext velocityContext = VelocityUtils.createVelocityContextWithTools();
            velocityContext.put("patient", d);
            velocityContext.put("currentDate", sdf.format(new Date()));
            Provider mrp = null;
            if (d.getProviderNo() != null && d.getProviderNo().length() > 0) {
                mrp = providerDao.getProvider(d.getProviderNo());
            } else {
                mrp = providerDao.getProvider(OscarProperties.getInstance().getProperty("orn.default_mrp", ""));
            }
            velocityContext.put("mrp", mrp);

            final String mrp1 = mrp.getFullName();

            final String letter = VelocityUtils.velocityEvaluate(velocityContext, template);

            JavaMailSender mailSender = (JavaMailSender) SpringUtils.getBean("mailSender");

            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setTo(d.getEmail());
                    message.setSubject(OscarProperties.getInstance().getProperty("orn.email.subject",
                            "Important Message from " + mrp1));
                    message.setFrom(OscarProperties.getInstance().getProperty("orn.email.from",
                            "no-reply@oscarmcmaster.org"));
                    message.setText(letter, true);
                }
            };
            mailSender.send(preparator);

        } catch (IOException e) {
            MiscUtils.getLogger().error("Error", e);
            success = false;
            error = e.getMessage();
        } finally {
            OscarAuditLogger.getInstance().log("create", "CkdPatientLetter", Integer.valueOf(demographicNo),
                    "");
            OscarAuditLogger.getInstance().log("email", "CkdPatientLetter", Integer.valueOf(demographicNo), "");
        }
    }
    json.put("success", String.valueOf(success));
    json.put("error", error);
    try {
        json.write(response.getWriter());
    } catch (IOException e) {
        MiscUtils.getLogger().error("error", e);
    }
    return null;
}

From source file:org.patientview.monitoring.ImportMonitor.java

public static void sendEmail(String from, String[] to, String[] bcc, String subject, String body) {
    if (StringUtils.isBlank(from)) {
        throw new IllegalArgumentException("Cannot send mail missing 'from'");
    }/*from  www  . j a v a  2s  .c  o  m*/

    if ((to == null || to.length == 0) && (bcc == null || bcc.length == 0)) {
        throw new IllegalArgumentException("Cannot send mail missing recipients");
    }

    if (StringUtils.isBlank(subject)) {
        throw new IllegalArgumentException("Cannot send mail missing 'subject'");
    }

    if (StringUtils.isBlank(body)) {
        throw new IllegalArgumentException("Cannot send mail missing 'body'");
    }

    ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath*:context-standalone.xml" });

    JavaMailSender javaMailSender = (JavaMailSender) context.getBean("javaMailSender");

    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper messageHelper;

    try {
        messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setTo(to);
        if (bcc != null && bcc.length > 0) {
            Address[] bccAddresses = new Address[bcc.length];
            for (int i = 0; i < bcc.length; i++) {
                bccAddresses[i] = new InternetAddress(bcc[i]);
            }
            message.addRecipients(Message.RecipientType.BCC, bccAddresses);
        }
        messageHelper.setFrom(from);
        messageHelper.setSubject(subject);
        messageHelper.setText(body, false); // Note: the second param indicates to send plaintext

        javaMailSender.send(messageHelper.getMimeMessage());

        LOGGER.info("Sent an email about Importer issues. From: {} To: {}", from, Arrays.toString(to));
    } catch (Exception e) {
        LOGGER.error("Could not send email: {}", e);
    }
}