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:com.seajas.search.attender.service.mail.MailService.java

/**
 * Send an e-mail message.//  w  ww.j ava 2  s  . c o  m
 * 
 * @param receiver
 * @param textContent
 * @param htmlContent
 */
public boolean sendMessage(final String receiver, final String subject, final String textContent,
        final String htmlContent) {
    MimeMessage message = sender.createMimeMessage();

    // We request a multi-part message so we can write out both HTML and text

    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(fromAddress);
        helper.setTo(receiver);
        helper.setSubject(subject);
        helper.setText(textContent, htmlContent);

        sender.send(message);

        return true;
    } catch (MessagingException e) {
        logger.error("Could not build the given e-mail message for receiver '" + receiver + "'", e);
    } catch (MailException e) {
        logger.error("Could not send the givn e-mail message for receiver '" + receiver + "'", e);
    }

    return false;
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping("/resetPassword")
public void doPost(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "verify", required = false) String verify,
        @RequestParam(value = "username", required = false) String username, Locale locale) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    String word = null;/*ww w  .j  a  va2s. c  o  m*/
    if (session != null) {
        word = (String) session.getAttribute("word");
        session.removeAttribute("word");
    }
    if (word == null || !word.equalsIgnoreCase(verify)) {
        out.print("alert('??');");
        return;
    }

    User user = userMapper.findOne(username);
    if (user == null) {
        out.print("alert('?');");
        return;
    }
    String email = user.getEmail();
    if (email == null || !email.toLowerCase().matches(ValueCheck.EMAIL_PATTERN)) {
        out.print(
                "alert('???????');");
        return;
    }
    try {
        String vc = user.getVcode();
        if (vc == null || user.getExpireTime() != null && user.getExpireTime().compareTo(Instant.now()) < 0) {
            vc = Utility.getRandomString(16);
        }
        user = user.toBuilder().vcode(vc).expireTime(Instant.now().plus(1, ChronoUnit.HOURS)).build();
        userMapper.update(user);
        String url = getPath(request, "/resetPassword.html?vc=", vc + "&u=", user.getId());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("url", url);
        map.put("ojName", judgeConfiguration.getContextPath() + " OJ");

        String content = templateEngine.process("users/password", new Context(locale, map));
        String title = templateEngine.process("users/passwordTitle", new Context(locale, map));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo(email);
        helper.setSubject(title);
        helper.setText(content, true);
        helper.setFrom(javaMailSender.getUsername());

        javaMailSender.send(mimeMessage);
    } catch (MailException | MessagingException ex) {
        log.error("", ex);
        out.print("alert('?????')");
        return;
    }
    out.print("alert('???" + user.getEmail() + "??');");
}

From source file:nu.yona.server.email.EmailService.java

public void prepareMimeMessage(MimeMessage mimeMessage, String senderName, InternetAddress receiverAddress,
        String subjectTemplateName, String bodyTemplateName, Map<String, Object> templateParameters)
        throws MessagingException, UnsupportedEncodingException {
    Context ctx = ThymeleafUtil.createContext();
    ctx.setVariable("includedMediaBaseUrl", yonaProperties.getEmail().getIncludedMediaBaseUrl());
    ctx.setVariable("appleAppStoreUrl", yonaProperties.getEmail().getAppleAppStoreUrl());
    ctx.setVariable("googlePlayStoreUrl", yonaProperties.getEmail().getGooglePlayStoreUrl());
    templateParameters.entrySet().stream().forEach(e -> ctx.setVariable(e.getKey(), e.getValue()));

    String subjectText = emailTemplateEngine.process(subjectTemplateName + ".txt", ctx);
    String bodyText = emailTemplateEngine.process(bodyTemplateName + ".html", ctx);

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(new InternetAddress(yonaProperties.getEmail().getSenderAddress(), senderName));
    message.setTo(receiverAddress);/*from   w  w  w  . j  a v  a 2 s .com*/
    message.setSubject(subjectText);
    message.setText(bodyText, true);
}

From source file:com.github.dbourdette.otto.service.mail.Mailer.java

public void send(Mail mail) throws MessagingException, UnsupportedEncodingException {
    MailConfiguration configuration = findConfiguration();

    JavaMailSender javaMailSender = mailSender(configuration);

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
    helper.setSubject(mail.getSubject());
    helper.setFrom(configuration.getSender());

    for (String name : StringUtils.split(mail.getTo(), ",")) {
        helper.addTo(name);//from   w w  w  . j a  v a 2  s.com
    }

    helper.setText(mail.getHtml(), true);

    javaMailSender.send(mimeMessage);
}

From source file:com.github.dactiv.common.spring.mail.JavaMailService.java

/**
 * ??//from w ww . j  a  va 2  s .  c  o  m
 * 
 * @param sendTo ??
 * @param sendFrom ?
 * @param subject 
 * @param content 
 * @param attachment mapkey????value?????
 */
private void doSend(String sendTo, String sendFrom, String subject, String content,
        Map<String, File> attachment) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, encoding);

        helper.setTo(sendTo);
        helper.setFrom(sendFrom);
        helper.setSubject(subject);
        helper.setText(content, true);

        if (!MapUtils.isEmpty(attachment)) {
            for (Entry<String, File> entry : attachment.entrySet()) {
                helper.addAttachment(entry.getKey(), entry.getValue());
            }
        }

        mailSender.send(msg);
        logger.info("???");
    } catch (MessagingException e) {
        logger.error("", e);
    } catch (Exception e) {
        logger.error("??", e);
    }
}

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

/**
 * {@inheritDoc}//from   w  w w. j a va  2  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:eionet.meta.service.EmailServiceImpl.java

/**
 * {@inheritDoc}/*ww  w .j  ava2s .  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:br.ufc.ivela.commons.mail.MailService.java

public List<MimeMessage> send(String[] to, String from, String subject, String content)
        throws MessagingException {

    if (to == null || to.length <= 0) {
        throw new IllegalArgumentException("You cannot send an email without recipients");
    }//w w w  .j av a 2s.  c  o m

    if (from == null || from.isEmpty()) {
        throw new IllegalArgumentException("You cannot send an email without a sender");
    }

    if (subject == null || subject.isEmpty()) {
        throw new IllegalArgumentException("You cannot send an email without a subject");
    }

    content = content != null ? content : "";

    // Construct the message
    MimeMessage[] messagesToSend = new MimeMessage[to.length];

    for (int i = 0; i < to.length; i++) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setTo(to[i]);
        helper.setFrom(from);
        helper.setSubject(subject);
        helper.setText(content, true);
        messagesToSend[i] = message;
    }

    List<MimeMessage> messagesNotSent = new ArrayList<MimeMessage>(messagesToSend.length);

    if (disabled)
        return messagesNotSent;

    for (MimeMessage message : messagesToSend) {
        try {
            this.mailSender.send(message);
        } catch (Exception e) {
            log.error("Error sending Email to:" + message.toString(), e);
            messagesNotSent.add(message);
        }
    }

    return messagesNotSent;
}

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;/*from ww w  .  ja  v  a  2s . c om*/
    }
    // 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:com.oakhole.core.email.MimeMailService.java

/**
 * ??MIME?./*from w ww.j  a va 2s .  c  o  m*/
 */
public void sendNotificationMail() {

    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);

        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        //
        String content = generateContent();
        helper.setText(content, true);
        //
        File attachment = generateAttachment();
        helper.addAttachment(attachment.getName(), attachment);

        mailSender.send(msg);
        logger.info("HTML??{}", to);
    } catch (MessagingException e) {
        logger.error("", e);
    } catch (Exception e) {
        logger.error("??", e);
    }
}