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 plainText, String htmlText) throws MessagingException 

Source Link

Document

Set the given plain text and HTML text as alternatives, offering both options to the email client.

Usage

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

public TaskExec executeSingle(final NotificationTask task) {
    init();/*from   w  ww .  ja  v a 2  s .c  om*/

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

    boolean retryPossible = true;

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

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

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

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

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

                mailSender.send(message);

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

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

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

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

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

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

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

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

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

    return execution;
}

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

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

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

    boolean retryPossible = true;

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

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

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

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

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

                mailSender.send(message);

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

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

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

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

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

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

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

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

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

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

    return execution;
}

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

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

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

    boolean retryPossible = true;

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

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

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

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

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

                mailSender.send(message);

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

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

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

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

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

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

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

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

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

    return execution;
}

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

@Transactional
public TaskExec executeSingle(final NotificationTask task) {
    TaskExec execution = entityFactory.newEntity(TaskExec.class);
    execution.setTask(task);/*  w  ww. j  a v  a  2  s .c  o  m*/
    execution.setStart(new Date());

    boolean retryPossible = true;

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

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

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

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

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

                mailSender.send(message);

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

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

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

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

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

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

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

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

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

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

    return execution;
}

From source file:org.apereo.portal.portlets.account.EmailPasswordResetNotificationImpl.java

@Override
public void sendNotification(URL resetUrl, ILocalAccountPerson account, Locale locale) {
    log.debug("Sending password reset instructions to user with url {}", resetUrl.toString());

    try {/*from  w  w  w . j a v  a 2s .co  m*/
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String email = (String) account.getAttributeValue(ILocalAccountPerson.ATTR_MAIL);
        String subject = messageSource.getMessage(subjectMessageKey, new Object[] {}, locale);
        String body = formatBody(resetUrl, account, locale);

        helper.addTo(email);
        helper.setText(body, true);
        helper.setSubject(subject);
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to {} from {} subject {}", email, Arrays.toString(message.getFrom()),
                message.getSubject());
        this.mailSender.send(helper.getMimeMessage());

    } catch (Exception e) {
        log.error("Unable to send password reset email", e);
    }
}

From source file:org.beangle.notification.notifiers.mail.AbstractMailNotifier.java

public void deliver(T mailMsg) throws NotificationException {
    MimeMessage mimeMsg = mailSender.createMimeMessage();
    try {// ww w .  ja  va 2s.c  om
        if (null == mailMsg.getSendAt()) {
            mimeMsg.setSentDate(new Date());
        } else {
            mimeMsg.setSentDate(mailMsg.getSendAt());
        }
        MimeMessageHelper messageHelper = null;
        String encoding = StringUtils.substringAfter(mailMsg.getContentType(), "charset=");
        if (StringUtils.isEmpty(encoding)) {
            messageHelper = new MimeMessageHelper(mimeMsg);
        } else {
            messageHelper = new MimeMessageHelper(mimeMsg, encoding);
        }
        messageHelper.setText(buildText(mailMsg), StringUtils.contains(mailMsg.getContentType(), "html"));
        String subject = buildSubject(mailMsg);
        messageHelper.setSubject(subject);
        int recipients = addRecipient(mimeMsg, mailMsg);
        beforeSend(mailMsg, mimeMsg);
        if (recipients > 0) {
            mailSender.send(mimeMsg);
            if (logger.isDebugEnabled()) {
                logger.debug("mail sended from {} to {} with subject {}",
                        new Object[] { from, mailMsg.getRecipients(), subject });
            }
        } else {
            logger.warn("{} without any recipients ,sending aborted!", subject);
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailMsg, mimeMsg);
}

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

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

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

}

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

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

    try {//w  w  w  .  j a  v  a  2  s .  co  m
        if (addAttachments) {
            messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
        } else {
            messageHelper = new MimeMessageHelper(mailSender.createMimeMessage());
        }

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

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

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

    return messageHelper.getMimeMessage();
}

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

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

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

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

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