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.thingsboard.server.service.mail.DefaultMailService.java

private void sendMail(JavaMailSenderImpl mailSender, String mailFrom, String email, String subject,
        String message) throws ThingsboardException {
    try {//from  www .  j a  v a  2s  .c  o m
        MimeMessage mimeMsg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, UTF_8);
        helper.setFrom(mailFrom);
        helper.setTo(email);
        helper.setSubject(subject);
        helper.setText(message, true);
        mailSender.send(helper.getMimeMessage());
    } catch (Exception e) {
        throw handleException(e);
    }
}

From source file:org.yes.cart.service.mail.impl.MailComposerImpl.java

/**
 * Fill mail message. At least one of the templates must be given.
 *
 * @param helper          mail message helper
 * @param textTemplate    optional text template
 * @param htmlTemplate    optional html template
 * @param mailTemplateChain path to template folder
 * @param shopCode        shop code/*from   ww w.  java 2 s  .  com*/
 * @param locale          locale
 * @param templateName    template name
 * @param model           model
 *
 * @throws MessagingException     in case if message can not be composed
 * @throws java.io.IOException    in case of inline resources can not be found
 * @throws ClassNotFoundException in case if something wrong with template engine
 */
void composeMessage(final MimeMessageHelper helper, final String textTemplate, final String htmlTemplate,
        final List<String> mailTemplateChain, final String shopCode, final String locale,
        final String templateName, final Map<String, Object> model)
        throws MessagingException, ClassNotFoundException, IOException {

    if (textTemplate == null || htmlTemplate == null) {
        if (textTemplate != null) {
            helper.setText(merge(textTemplate, model), false);
        }

        if (htmlTemplate != null) {
            helper.setText(merge(htmlTemplate, model), true);
            inlineResources(helper, htmlTemplate, mailTemplateChain, shopCode, locale, templateName);
        }

    } else {
        helper.setText(merge(textTemplate, model), merge(htmlTemplate, model));
        inlineResources(helper, htmlTemplate, mailTemplateChain, shopCode, locale, templateName);
    }

}

From source file:org.yes.cart.service.mail.impl.MailComposerImpl.java

/** {@inheritDoc} */
@Override/*from  w ww.  ja  v a  2 s . c  o  m*/
public void convertMessage(final Mail mail, final MimeMessage mimeMessage)
        throws MessagingException, IOException, ClassNotFoundException {

    final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

    helper.setTo(mail.getRecipients());

    helper.setSentDate(new Date());

    if (mail.getCc() != null) {
        helper.setCc(mail.getCc());
    }

    if (mail.getBcc() != null) {
        helper.setBcc(mail.getBcc());
    }

    final String textTemplate = mail.getTextVersion();
    final String htmlTemplate = mail.getHtmlVersion();

    helper.setSubject(mail.getSubject());
    helper.setFrom(mail.getFrom());

    if (textTemplate == null || htmlTemplate == null) {
        if (textTemplate != null) {
            helper.setText(textTemplate, false);
        }

        if (htmlTemplate != null) {
            helper.setText(htmlTemplate, true);
            inlineResources(helper, mail);
        }

    } else {
        helper.setText(textTemplate, htmlTemplate);
        inlineResources(helper, mail);
    }

}

From source file:se.vgregion.webbisar.presentation.WebbisarFlowSupportBean.java

public MailMessageResultBean sendWebbis(final Long webbisId, final MailMessageBean mailMessageBean)
        throws WebbisNotFoundException {

    // Validate email adresses first
    MailMessageResultBean result = validateEmailAddresses(mailMessageBean);
    if (Boolean.FALSE.equals(result.getSuccess())) {
        return result;
    }//from   w  ww . j  a v a 2  s  .c o m
    // Validate sender name
    if (StringUtils.isBlank(mailMessageBean.getSenderName())) {
        result.setSuccess(Boolean.FALSE);
        result.setMessage("Namn p avsndare mste anges.");
        return result;
    }

    // use this map to store the information that will be merged into the html template
    Map<String, String> emailInformation = new HashMap<String, String>();
    WebbisBean webbisBean = getWebbis(webbisId, null, null, null, null);
    Map<Long, String> webbisarIdNames = webbisBean.getMultipleBirthSiblingIdsAndNames();

    String messageText = mailMessageBean.getMessage();
    if (!StringUtils.isEmpty(messageText)) {
        messageText = messageText.replace("\r", "").replace("\n", "<br/>");
    }

    // add the current webbis to the list of siblings so that
    // we have them all in the same Map
    webbisarIdNames.put(webbisBean.getId(), webbisBean.getName());

    // add the message and the base url for html links
    emailInformation.put("baseUrl", cfg.getExternalBaseUrl());
    emailInformation.put("message", messageText);
    emailInformation.put("senderName", mailMessageBean.getSenderName());
    emailInformation.put("senderAddress", mailMessageBean.getSenderAddress());

    VelocityContext context = new VelocityContext();
    context.put("emailInfo", emailInformation);
    context.put("webbisInfo", webbisarIdNames);

    Template template = null;
    StringWriter msgWriter = null;
    try {
        velocityEngine.init();
        template = velocityEngine.getTemplate(cfg.getMailTemplate());
        msgWriter = new StringWriter();
        template.merge(context, msgWriter);
    } catch (Exception e1) {
        LOGGER.error("Failed to get/merge velocity template.", e1);
        result.setSuccess(Boolean.FALSE);
        result.setMessage("Internt fel, webbis kunde inte skickas.");
        return result;
    }
    String msgText = msgWriter.toString();

    // Seems OK, try to send mail...
    try {
        InternetAddress fromAddress = null;
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, ENCODING_UTF8);
        try {
            fromAddress = new InternetAddress(cfg.getMailFromAddress(), cfg.getMailFromAddressName());
        } catch (UnsupportedEncodingException e) {
            fromAddress = new InternetAddress(cfg.getMailFromAddress());
        }
        helper.setTo(mailMessageBean.getRecipientAddresses().split(","));
        helper.setFrom(fromAddress);
        helper.setSubject(mailMessageBean.getSubject());
        helper.setText(msgText, true);

        // include the vgr logo
        String logoPath = cfg.getMultimediaFileBaseDir() + "/" + cfg.getMailLogo();
        FileSystemResource res = new FileSystemResource(new File(logoPath));
        helper.addInline("imageIdentifier", res);

        mailSender.send(mimeMessage);
    } catch (MailException ex) {
        LOGGER.error("Failed to create/send mail.", ex);
        result.setSuccess(Boolean.FALSE);
        result.setMessage("Internt fel, webbis kunde inte skickas.");
        return result;
    } catch (MessagingException e) {
        LOGGER.error("Failed to create/send mail.", e);
        result.setSuccess(Boolean.FALSE);
        result.setMessage("Internt fel, webbis kunde inte skickas.");
        return result;
    }

    // ...and all was well...
    result.setSuccess(Boolean.TRUE);
    result.setMessage("Webbis skickad!");
    return result;
}

From source file:siddur.solidtrust.scrape.ScrapeMonitor.java

private void send(boolean alert1, boolean alert2, int marktplaats, int autoscout) {
    MimeMessage message = mailSender.createMimeMessage();
    try {/*from w w  w.  j a  v a 2 s .  c  o  m*/
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("gbg1_spsms_gtrak@pactera-pgs-mail.chinacloudapp.cn", "Solidtrust Admin");
        if (alert1 || alert2) {
            log4j.info("Send email to alert that data scraped very little");
            helper.setTo(SolidtrustConstants.BEN_EMAIL);
            helper.setCc(SolidtrustConstants.MY_EMAIL);
        } else {
            helper.setTo(SolidtrustConstants.MY_EMAIL);
        }
        helper.setSubject("Little data scraped alert");

        StringBuilder sb = new StringBuilder();
        sb.append(
                "<html><body><table border='1' cellspacing='0'><tr><td>Source</td><td>Amount Today</td><td>Normal amount daily</td></tr>");
        sb.append("<tr><td>Martplaats</td><td>{0}</td><td>9000</td></tr>");
        sb.append("<tr><td>AutoscoutNl</td><td>{1}</td><td>250</td></tr>");
        sb.append("</table></body></html>");
        helper.setText(MessageFormat.format(sb.toString(),
                alert1 ? "<font color='red'>" + marktplaats + "</font>" : marktplaats,
                alert2 ? "<font color='red'>" + autoscout + "</font>" : autoscout), true);
        mailSender.send(message);
    } catch (Exception e) {
        log4j.error(e.getMessage(), e);
    }
}

From source file:siddur.solidtrust.wok.WokController.java

@Scheduled(cron = "0 5 1 2 * ?") //01:05 2th monthly
@RequestMapping("notify")
public void sendMail() throws Exception {
    Calendar today = Calendar.getInstance();
    int year = today.get(Calendar.YEAR);
    int month = today.get(Calendar.MONTH);
    String filename = year + "-" + month + ".xlsx";
    File file = new File(FileSystemUtil.getWokDir(), filename);
    generateFile(year, month, file);/*ww  w.j  a  va  2s .c om*/

    log4j.info("Send email for WOK records: " + file.getName());
    MimeMessage message = mailSender.createMimeMessage();

    // use the true flag to indicate you need a multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom("gbg1_spsms_gtrak@pactera-pgs-mail.chinacloudapp.cn", "Solidtrust Admin");
    helper.setTo(SolidtrustConstants.WOK_EMAIL);
    helper.addCc(SolidtrustConstants.BEN_EMAIL);
    helper.addCc(SolidtrustConstants.MY_EMAIL);
    helper.setSubject(MessageFormat.format("WOK[{0}]", (year + "-" + month)));

    // use the true flag to indicate the text included is HTML
    helper.setText("<html><body>Here is WOK data of last month. Thanks.</body></html>", true);

    // let's include the infamous windows Sample file (this time copied to c:/)
    FileSystemResource res = new FileSystemResource(file);
    helper.addAttachment(file.getName(), res);

    mailSender.send(message);
}