Example usage for org.springframework.mail.javamail MimeMessageHelper setTo

List of usage examples for org.springframework.mail.javamail MimeMessageHelper setTo

Introduction

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

Prototype

public void setTo(String[] to) throws MessagingException 

Source Link

Usage

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

/**
 * {@inheritDoc}/*from   ww  w  . j a v a2  s.  c o  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:de.thm.arsnova.services.UserService.java

private void sendEmail(DbUser dbUser, String subject, String body) {
    MimeMessage msg = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
    try {//w ww  .ja v a 2  s  .  c o  m
        helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">");
        helper.setTo(dbUser.getUsername());
        helper.setSubject(subject);
        helper.setText(body);

        LOGGER.info("Sending mail \"{}\" from \"{}\" to \"{}\"",
                new Object[] { subject, msg.getFrom(), dbUser.getUsername() });
        mailSender.send(msg);
    } catch (MessagingException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    } catch (MailException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    }
}

From source file:com.pamarin.income.controller.SuggestionCtrl.java

private void sendEmail2User() {
    mailSender.send(new MailCallback() {

        @Override//from  ww w  . j a v a 2  s  .c  om
        public void execute(MimeMessageHelper helper) throws Exception {
            helper.setSubject("" + app.getName());
            helper.setText(
                    " ??");
            helper.setTo(SecurityUtils.getUser().getUsername());
        }
    });
}

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

/**
 * {@inheritDoc}/*w  ww.j ava 2s  .  c  o m*/
 */
@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.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}/*from  w  w  w.j a v a 2  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.JuggerBo.java

/**
 * General jugger mail sender/*from   www  .  j a  va  2s. c o m*/
 *
 * @param jugger
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Jugger jugger, final String baseUrl, final String subject, final String oneWayCode,
        final String template) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(jugger.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("jugger", jugger);
            model.put("baseUrl", baseUrl);
            model.put("oneWayCode", URLEncoder.encode(oneWayCode, "UTF-8"));
            model.put("username", URLEncoder.encode(jugger.getUser().getUsername(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}

From source file:info.jtrac.mail.MailSender.java

public void send(Item item) {
    if (sender == null) {
        logger.debug("mail sender is null, not sending notifications");
        return;// w  w w  . j  a  v a2s  .  c  o  m
    }
    // TODO make this locale sensitive per recipient        
    logger.debug("attempting to send mail for item update");
    // prepare message content
    StringBuffer sb = new StringBuffer();
    String anchor = getItemViewAnchor(item, defaultLocale);
    sb.append(anchor);
    sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale));
    sb.append(anchor);
    if (logger.isDebugEnabled()) {
        logger.debug("html content: " + sb);
    }
    // prepare message
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
    try {
        helper.setText(addHeaderAndFooter(sb), true);
        helper.setSubject(getSubject(item));
        helper.setSentDate(new Date());
        helper.setFrom(from);
        // set TO            
        if (item.getAssignedTo() != null) {
            helper.setTo(item.getAssignedTo().getEmail());
        } else {
            helper.setTo(item.getLoggedBy().getEmail());
        }
        // set CC
        if (item.getItemUsers() != null) {
            String[] cc = new String[item.getItemUsers().size()];
            int i = 0;
            for (ItemUser itemUser : item.getItemUsers()) {
                cc[i++] = itemUser.getUser().getEmail();
            }
            helper.setCc(cc);
        }
        // send message
        sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:csns.util.EmailUtils.java

public boolean sendHtmlMail(Email email) {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);

    try {/*from w  w w . j  a  v  a 2s. co  m*/
        message.setContent(getHtml(email), "text/html");

        helper.setSubject(email.getSubject());
        helper.setFrom(email.getAuthor().getPrimaryEmail());
        helper.setCc(email.getAuthor().getPrimaryEmail());
        String addresses[] = getAddresses(email.getRecipients(), email.isUseSecondaryEmail())
                .toArray(new String[0]);
        if (addresses.length > 1) {
            helper.setTo(appEmail);
            helper.setBcc(addresses);
        } else
            helper.setTo(addresses);

        mailSender.send(message);

        logger.info(email.getAuthor().getUsername() + " sent email to "
                + StringUtils.arrayToCommaDelimitedString(addresses));

        return true;
    } catch (MessagingException e) {
        logger.warn("Fail to send MIME message", e);
    }

    return false;
}

From source file:com.pamarin.income.controller.SuggestionCtrl.java

private void sendEmail2Admin(final File attachFile) {
    mailSender.send(new MailCallback() {

        @Override//from  w ww . j  ava2s  .  c  om
        public void execute(MimeMessageHelper helper) throws Exception {
            if (attachFile != null) {
                FileSystemResource file = new FileSystemResource(attachFile);
                helper.addAttachment(attachFile.getName(), file);
            }

            helper.setSubject("?" + app.getName());
            helper.setText(getSuggestion().getType() + " : " + getSuggestion().getMessage());
            helper.setTo(destinationReceiveEmail);
        }
    });
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void addMailRecipients(ReportJobMailNotification mailNotification, MimeMessageHelper messageHelper)
        throws MessagingException {
    List toAddresses = mailNotification.getToAddresses();
    if (toAddresses != null && !toAddresses.isEmpty()) {
        String[] addressArray = new String[toAddresses.size()];
        toAddresses.toArray(addressArray);
        messageHelper.setTo(addressArray);
    }//from w  w  w . jav  a  2  s  .  c  o  m

    List ccAddresses = mailNotification.getCcAddresses();
    if (ccAddresses != null && !ccAddresses.isEmpty()) {
        String[] addressArray = new String[ccAddresses.size()];
        ccAddresses.toArray(addressArray);
        messageHelper.setCc(addressArray);
    }
    List bccAddresses = mailNotification.getBccAddresses();
    if (bccAddresses != null && !bccAddresses.isEmpty()) {
        String[] addressArray = new String[bccAddresses.size()];
        bccAddresses.toArray(addressArray);
        messageHelper.setBcc(addressArray);
    }
}