Example usage for org.springframework.mail SimpleMailMessage getText

List of usage examples for org.springframework.mail SimpleMailMessage getText

Introduction

In this page you can find the example usage for org.springframework.mail SimpleMailMessage getText.

Prototype

@Nullable
    public String getText() 

Source Link

Usage

From source file:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email/*w ww.ja  va  2 s .c om*/
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

    } catch (MessagingException me) {
        throw new ServiceException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}

From source file:cherry.foundation.mail.MailSendHandlerImpl.java

private void send(final SimpleMailMessage msg, final AttachmentPreparator preparator) {
    if (preparator == null) {
        mailSender.send(msg);// w  w  w .j a v a 2s .co m
    } else {
        mailSender.send(new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setTo(msg.getTo());
                helper.setCc(msg.getCc());
                helper.setBcc(msg.getBcc());
                helper.setFrom(msg.getFrom());
                helper.setSubject(msg.getSubject());
                helper.setText(msg.getText());
                preparator.prepare(new Attachment(helper));
            }
        });
    }
}

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(simpleMailMessage.getTo());

            // The "from" field is required
            if (simpleMailMessage.getFrom() == null) {
                simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL);
            }/*  w ww  . jav  a 2s.  c om*/

            message.setFrom(simpleMailMessage.getFrom());
            message.setSubject(simpleMailMessage.getSubject());

            // Map all the fields for the email template
            Map<String, Object> model = new HashMap<String, Object>();

            // Add the host name into the footer of the email
            String host = InetAddress.getLocalHost().getHostName();

            // Message title
            model.put("title", "Message from The ARK");
            // Message header
            model.put("header", "Message from The ARK");
            // Message subject
            model.put("subject", simpleMailMessage.getSubject());
            // Message text
            model.put("text", simpleMailMessage.getText());
            // Hostname in message footer
            model.put("host", host);

            // TODO: Add inline image(s)??
            // Add inline image header
            // FileSystemResource res = new FileSystemResource(new
            // File("c:/Sample.jpg"));
            // message.addInline("bgHeaderImg", res);

            // Set up the email text
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "au/org/theark/core/velocity/resetPasswordEmail.vm", model);
            message.setText(text, true);
        }
    };

    // send out the email
    javaMailSender.send(preparator);
}

From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java

@Override
public boolean sendForgottenPasswordMail(String email, String plainPassword) {
    log.debug("Creating new mail object");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);

    log.debug("Composing e-mail - TO: " + email);

    String subject = mail.getSubject() + " - Password reset";
    log.debug("Composing e-mail - SUBJECT: " + subject);
    mail.setSubject(subject);/*from   w  w w.  j a v  a  2  s. c om*/

    String text = "Your password for EEGbase portal was reset. Your new password (within brackets) is ["
            + plainPassword + "]\n\n" + "Please change the password after logging into system.";
    log.debug("Composing e-mail - TEXT: " + text);
    mail.setText(text);

    return sendEmail(email, mail.getSubject(), mail.getText());
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/*from ww w  . ja  v  a 2 s . c o  m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendForumPostReplyNotificationMessage(ForumPostNotified forumPostReplied, ForumPost forumPost,
        User currentUser) {
    try {
        if (!StringUtils.isBlank(currentUser.getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(currentUser.getMail());
            if (!Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) {
                // message for a reply post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.forumPostReplyNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(),
                                        forumPost.getParentPost().getSubject() },
                                "{", "}"));
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.forumPostReplyNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getParentPost().getSubject(),
                                getForumTopicUrl(forumPost.getTopic(),
                                        Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) },
                        "{", "}"));
            } else {
                // message for a course transcription post or a course question post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.courseTranscriptionNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(), forumPost.getTopic().getSubject() },
                                "{", "}"));

                CourseTopicOption courseTopicOption = getCourseTopicOptionDAO()
                        .getOption(forumPost.getTopic().getTopicId());
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.courseTranscriptionNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getTopic().getSubject(), getCourseTopicUrl(courseTopicOption) },
                        "{", "}"));
            }

            //getJavaMailSender().send(message);
            //instead of sending the message by email sending it by internal message

            // Composing Message
            UserMessage userMessage = new UserMessage();
            userMessage.setSender("Staff");
            User tempUser = currentUser;
            userMessage.setRecipient(tempUser.getAccount());
            userMessage.setSubject(message.getSubject());
            userMessage.setBody(message.getText());
            userMessage.setMessageId(null);
            userMessage.setRecipientStatus(RecipientStatus.NOT_READ);
            userMessage.setSendedDate(new Date());

            //Sending Message
            getCommunityService().createNewMessage(userMessage);

        } else {
            logger.error("Mail for ForumPost reply not sended for user " + currentUser.getAccount()
                    + ". Check mail field on tblUser for account " + currentUser.getAccount());
        }

        forumPostReplied.setMailSended(Boolean.TRUE);
        forumPostReplied.setMailSendedDate(new Date());

        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.uhp.portlets.news.service.NotificationServiceImpl.java

private void sendDailyEmailForTopics(final Category category) {

    final List<Topic> topicsForToday = this.getPendingTopics(category.getCategoryId());

    if (topicsForToday.size() < 1) {
        return;//w w w .ja v  a 2  s.  c o  m
    }

    final List<IEscoUser> managers = this.getOnlyTopicManagersForTopics(category.getCategoryId(),
            topicsForToday);

    if (managers.isEmpty()) {
        return;
    }
    for (IEscoUser user : managers) {
        if (user.getEmail() != null && user.getEmail().length() > 0) {
            SimpleMailMessage message = new SimpleMailMessage(templateMessage);
            message.setTo(user.getEmail());
            String text = message.getText();
            List<Topic> userTopics = filterUserTopics(user, topicsForToday);
            String[] tIds = new String[userTopics.size()];
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (Topic t : userTopics) {
                tIds[i++] = String.valueOf(t.getTopicId());
                sb.append(t.getName());
                sb.append(" [");
                int k = itemDao.getPendingItemsCountByTopic(t.getTopicId());
                sb.append(k + "]\n");

            }

            text = StringUtils.replace(text, "%NB%",
                    Integer.toString(this.itemDao.getPendingItemsCountByTopics(tIds)));
            text = StringUtils.replace(text, "%CATEGORY%", category.getName());
            text = StringUtils.replace(text, "%TOPICS%", sb.toString());
            message.setText(text);

            try {
                LOG.debug(message);
                this.mailSender.send(message);
            } catch (MailException e) {
                LOG.error("Notification Service:: An exception occured when sending mail, "
                        + "have you correctly configured your mail engine ?" + e);

            }
        }
    }

}

From source file:org.uhp.portlets.news.service.NotificationServiceImpl.java

private void sendDailyEmailForCategory(final Category category) {
    Long cId = category.getCategoryId();
    String n = "";
    LOG.debug("sendDailyEmailForCategory " + category.getName());
    List<Topic> topicsForToday = this.getPendingTopics(cId);
    if (topicsForToday.size() < 1) {
        LOG.debug("send Daily Email For Category [" + category.getName()
                + "] : nothing new, no notification sent");
        return;//w w w.ja v a 2  s .c  o  m
    }
    Set<IEscoUser> managers = this.getManagersForCategory(category);

    if (managers.isEmpty()) {
        return;
    }

    try {
        n = Integer.toString(this.itemDao.getPendingItemsCountByCategory(category.getCategoryId()));
    } catch (DataAccessException e1) {
        LOG.error("Notification error : " + e1.getMessage());

    }
    SimpleMailMessage message = new SimpleMailMessage(templateMessage);
    LOG.debug("send Daily Email For Category [" + category.getName() + "] : status OK");
    String[] recip = new String[managers.size()];
    int nb = 0;
    for (IEscoUser user : managers) {
        if (user.getEmail() != null && user.getEmail().length() > 0) {
            recip[nb++] = user.getEmail();
        }
    }

    message.setTo(recip);

    String text = message.getText();
    text = StringUtils.replace(text, "%NB%", n);
    text = StringUtils.replace(text, "%CATEGORY%", category.getName());
    text = StringUtils.replace(text, "%TOPICS%", this.getPendingTopicsForCategory(cId));
    message.setText(text);

    try {
        LOG.info(message);
        mailSender.send(message);
    } catch (MailException e) {
        LOG.error("Notification Service:: An exception occured when sending mail,"
                + " have you correctly configured your mail engine ?" + e);
    }

}

From source file:stroom.security.server.AuthenticationServiceMailSender.java

public void emailPasswordReset(final User user, final String password) {
    if (canEmailPasswordReset()) {
        // Add event log data for reset password.
        eventLog.resetPassword(user.getName(), true);

        final SimpleMailMessage mailMessage = new SimpleMailMessage();
        resetPasswordTemplate.copyTo(mailMessage);
        mailMessage.setTo(user.getName() + "@" + userDomain);

        String message = mailMessage.getText();
        message = StringUtils.replace(message, "\\n", "\n");
        message = StringUtils.replace(message, "${username}", user.getName());
        message = StringUtils.replace(message, "${password}", password);
        final HttpServletRequest req = httpServletRequestHolder.get();
        message = StringUtils.replace(message, "${hostname}", req.getServerName());

        mailMessage.setText(message);//from ww  w  . j  av  a2 s.c  o  m

        mailSender.send(mailMessage);
    }
}