Example usage for org.springframework.mail.javamail MimeMessagePreparator MimeMessagePreparator

List of usage examples for org.springframework.mail.javamail MimeMessagePreparator MimeMessagePreparator

Introduction

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

Prototype

MimeMessagePreparator

Source Link

Usage

From source file:eionet.meta.service.EmailServiceImpl.java

/**
 * {@inheritDoc}/*  ww  w. j  a  v  a  2  s  . com*/
 */
@Override
public void notifySiteCodeAllocation(String country, AllocationResult allocationResult, boolean adminRole)
        throws ServiceException {
    try {
        SiteCodeAllocationNotification notification = new SiteCodeAllocationNotification();
        notification.setAllocationTime(allocationResult.getAllocationTime().toString());
        notification.setUsername(allocationResult.getUserName());
        notification.setCountry(country);
        notification.setNofAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount()));
        notification.setTotalNofAllocatedCodes(
                Integer.toString(siteCodeDao.getCountryUnusedAllocations(country, false)));
        notification.setNofCodesAllocatedByEvent(Integer.toString(allocationResult.getAmount()));

        SiteCodeFilter filter = new SiteCodeFilter();
        filter.setDateAllocated(allocationResult.getAllocationTime());
        filter.setUserAllocated(allocationResult.getUserName());
        filter.setUsePaging(false);
        SiteCodeResult siteCodes = siteCodeDao.searchSiteCodes(filter);

        notification.setSiteCodes(siteCodes.getList());
        notification.setAdminRole(adminRole);

        final String[] to;
        // if test e-mail is provided, then do not send notification to actual receivers
        if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) {
            notification.setTest(true);
            notification.setTo(StringUtils.join(parseRoleAddresses(country), ","));
            to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ",");
        } else {
            to = parseRoleAddresses(country);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", notification);

        final String text = processTemplate("site_code_allocation.ftl", map);

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
                message.setText(text, false);
                message.setFrom(
                        new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM)));
                message.setSubject("Site codes allocated");
                message.setTo(to);
            }
        };
        mailSender.send(mimeMessagePreparator);

    } catch (Exception e) {
        throw new ServiceException("Failed to send allocation notification: " + e.toString(), e);
    }
}

From source file:com.ushahidi.swiftriver.core.mail.EmailHelper.java

private MimeMessagePreparator getMimeMessagePreparator(final User user, final String subject,
        final String mailBody) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper mimeHelper = new MimeMessageHelper(mimeMessage, true);
            mimeHelper.setFrom(senderAddress);
            mimeHelper.setTo(user.getEmail());
            mimeHelper.setReplyTo(senderAddress);
            mimeHelper.setSubject(subject);
            mimeHelper.setText(mailBody, true);
        }//from w  ww. j a  va2s . c  o  m
    };

    return preparator;
}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}/* w w w .  j ava  2  s.co  m*/
 * @see com.mobileman.projecth.business.MailManager#sendResetCredientialsEmail(User, String)
 */
@Override
public void sendResetCredientialsEmail(final User user, final String serverDnsName) {
    if (log.isDebugEnabled()) {
        log.debug("sendResetCredientialsEmail(" + user.getId() + ", " + serverDnsName + ") - start");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
            }

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setTo(user.getUserAccount().getEmail());
            messageHelper.setFrom("mitglied@projecth.com");
            messageHelper.setSubject("Passwort zurcksetzen");

            String tmpServerDnsName = serverDnsName;
            if (tmpServerDnsName == null || tmpServerDnsName.trim().length() == 0) {
                tmpServerDnsName = "projecth.de";
            }

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("user", user);
            model.put("dns_server_name", tmpServerDnsName);

            String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "reset-credentials-email-body.vm", model);
            String textMessage = HTMLTextParser.htmlToText(htmlMessage);
            messageHelper.setText(textMessage, htmlMessage);

            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
            }
        }
    };

    this.mailSender.send(preparator);

    if (log.isDebugEnabled()) {
        log.debug("sendResetCredientialsEmail(" + user.getId() + ") - end");
    }
}

From source file:com.marc.lastweek.business.services.mail.impl.MailServiceImpl.java

private MimeMessagePreparator getMimeMessagePreparator(final Locale locale, final String templateName,
        final Map<String, Object> templateData, final String mailTo) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            // Set message attributes
            message.setTo(mailTo);//from ww  w.  j av a 2  s  .  c  o m
            message.setFrom(MailServiceImpl.this.from);
            message.setSubject(getMailMessageEntry(locale, templateName + FIELD_SUBJECT));

            // Add parameters
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("locale", locale);
            model.put("dateTool", new DateTool());
            model.put("resourceTool", new ResourceTool());

            // Insert data in the template
            for (String name : templateData.keySet()) {
                model.put(name, templateData.get(name));
            }

            String text = VelocityEngineUtils.mergeTemplateIntoString(MailServiceImpl.this.velocityEngine,
                    MailServiceImpl.this.velocityTemplates.get(templateName), CHARSET, model);
            message.setText(text, true);

            // Insert stylesheet
            //ClassPathResource stylesheet = new ClassPathResource("templates/email.css", MailServiceImpl.class);
            //                ClassPathResource stylesheet = new ClassPathResource(MAIL_STYLESHEET, );
            //                message.addInline("email.css", stylesheet, "text/css");                        
        }
    };
    return preparator;
}

From source file:com.hmsinc.epicenter.webapp.PasswordResetController.java

/**
 * @param token/*from w ww  . j av  a  2s . c o  m*/
 * @param url
 */
private void sendPasswordResetEmail(final PasswordResetToken token, final String url) {

    final MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            final EpiCenterUser user = token.getUser();

            String encoding = "UTF-8";
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
                    MimeMessageHelper.MULTIPART_MODE_RELATED, encoding);
            message.setTo(user.getEmailAddress());
            message.setFrom(applicationProperties.getProperty("epicenter.mail.from"));
            message.setSubject(mailSubject);

            final Map<String, Object> model = new HashMap<String, Object>();
            model.put("url", url);
            model.put("username", user.getUsername());
            model.put("token", token.getToken());

            message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, TEMPLATE_TEXT, model),
                    VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, TEMPLATE_HTML, model));
        }
    };

    mailSender.send(preparator);
}

From source file:nl.surfnet.coin.teams.control.JoinTeamController.java

private void sendJoinTeamMessage(final Team team, final Person person, final String message,
        final Locale locale) throws IllegalStateException, IOException {

    Object[] subjectValues = { team.getName() };
    final String subject = messageSource.getMessage(REQUEST_MEMBERSHIP_SUBJECT, subjectValues, locale);

    final Set<Member> admins = grouperTeamService.findAdmins(team);
    if (CollectionUtils.isEmpty(admins)) {
        throw new RuntimeException("Team '" + team.getName() + "' has no admins to mail invites");
    }//from  w  w w. j  a v a 2s .  c  o  m

    final String html = composeJoinRequestMailMessage(team, person, message, locale, "html");
    final String plainText = composeJoinRequestMailMessage(team, person, message, locale, "plaintext");

    final List<InternetAddress> bcc = new ArrayList<InternetAddress>();
    for (Member admin : admins) {
        try {
            bcc.add(new InternetAddress(admin.getEmail()));
        } catch (AddressException ae) {
            log.debug("Admin has malformed email address", ae);
        }
    }
    if (bcc.isEmpty()) {
        throw new RuntimeException(
                "Team '" + team.getName() + "' has no admins with valid email addresses to mail invites");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);

}

From source file:eionet.meta.service.EmailServiceImpl.java

/**
 * {@inheritDoc}/*w  w  w  . ja v  a2  s. co  m*/
 */
@Override
public void notifySiteCodeReservation(String userName, int startIdentifier, int reserveAmount)
        throws ServiceException {
    try {
        SiteCodeAddedNotification notification = new SiteCodeAddedNotification();
        notification.setCreatedTime(new Date().toString());
        notification.setUsername(userName);
        notification.setNewCodesStartIdentifier(Integer.toString(startIdentifier));
        notification.setNofAddedCodes(Integer.toString(reserveAmount));
        notification.setNewCodesEndIdentifier(Integer.toString(startIdentifier + reserveAmount - 1));
        notification.setTotalNumberOfAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount()));

        final String[] to;
        // if test e-mail is provided, then do not send notification to actual receivers
        if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) {
            notification.setTest(true);
            notification.setTo(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO));
            to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ",");
        } else {
            to = StringUtils.split(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO), ",");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", notification);

        final String text = processTemplate("site_code_reservation.ftl", map);

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
                message.setText(text, false);
                message.setFrom(
                        new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM)));
                message.setSubject("New site codes added");
                message.setTo(to);
            }
        };
        mailSender.send(mimeMessagePreparator);

    } catch (Exception e) {
        throw new ServiceException("Failed to send new site codes reservation notification: " + e.toString(),
                e);
    }
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text,
        final Message previousMailMessage) {
    LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)");
    if (suppressMail) {
        return;/* w  ww . j a v  a 2 s  .co m*/
    }
    setMailProperties();
    MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) {
                setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses());
            }
            if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) {
                setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses());
            }
            if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) {
                setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses());
            }

            if (null != mailMetaData.getFromAddress()) {
                mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName())
                        .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress())
                        .append(MailConstants.GREATER_SYMBOL).toString()));
            }

            if (null != mailMetaData.getSubject() && null != text) {
                mimeMessage.setSubject(mailMetaData.getSubject());
            }

            if (null != text) {
                mimeMessage.setText(text);
            }

            // Create your new message part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE));

            // Create a multi-part to combine the parts
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create and fill part for the forwarded content
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(previousMailMessage.getDataHandler());

            // Add part to multi part
            multipart.addBodyPart(messageBodyPart);

            // Associate multi-part with message
            mimeMessage.setContent(multipart);

        }
    };
    try {
        mailSender.send(messagePreparator);
    } catch (MailException mailException) {
        LOGGER.error("Error while sending mail to configured mail account", mailException);
        throw new SendMailException(
                EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException);
    }
    LOGGER.info("mail sent successfully");
}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}//from  www . j  av  a2  s .  c  o m
 * @see com.mobileman.projecth.business.MailManager#sendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void sendMessage(final String senderEmail, final String receiverEmail, final String subject,
        final String body) {
    if (log.isDebugEnabled()) {
        log.debug("sendMessage(" + senderEmail + ", " + receiverEmail + ", " + subject + ", " + body
                + ") - start");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        /**
         * {@inheritDoc}
         * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
         */
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
            }

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setSubject(subject);
            messageHelper.setTo(receiverEmail);

            if (senderEmail == null || senderEmail.trim().length() == 0) {
                messageHelper.setFrom("projecth@projecth.com");
            } else {
                messageHelper.setFrom(senderEmail);
            }

            String textMessage = HTMLTextParser.htmlToText(body);
            messageHelper.setText(textMessage, body);

            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
            }
        }
    };

    this.mailSender.send(preparator);

    if (log.isDebugEnabled()) {
        log.debug("sendMessage(...) - end");
    }
}

From source file:it.jugpadova.blo.ParticipantBo.java

/**
 * General participant mail sender// ww w  . j a  va  2 s. co m
 *
 * @param participant
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Participant participant, final String baseUrl, final String subject,
        final String template, final Resource attachment, final String attachmentName) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("baseUrl", baseUrl);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
            if (attachment != null) {
                message.addAttachment(attachmentName, attachment);
            }
        }
    };
    this.mailSender.send(preparator);
}