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:cz.zcu.kiv.eegdatabase.logic.controller.article.AddArticleCommentController.java

private void sendNotification(String email, ArticleComment comment, HttpServletRequest request)
        throws MessagingException {
    String articleURL = "http://" + domain + "/articles/detail.html?articleId="
            + comment.getArticle().getArticleId();
    //System.out.println(articleURL);
    String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
            new String[] { comment.getArticle().getTitle(), comment.getPerson().getUsername() },
            RequestContextUtils.getLocale(request));
    //System.out.println(subject);
    String emailBody = "<html><body>";

    emailBody += "<p>"
            + messageSource.getMessage("articles.group.email.subscribtion.body.text.part1",
                    new String[] { comment.getArticle().getTitle() }, RequestContextUtils.getLocale(request))
            + "";
    emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />";
    emailBody += "<h3>Text:</h3> <p>" + comment.getText() + "</p><br />";
    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null,
            RequestContextUtils.getLocale(request)) + "</p>";
    emailBody += "</body></html>";

    //System.out.println(emailBody);
    log.debug("email body: " + emailBody);

    log.debug("Composing e-mail message");
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(mailMessage.getFrom());

    //  message.setContent("text/html");
    message.setTo(email);//from  ww  w .  ja v  a  2  s  .co  m
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);
    message.setText(emailBody, true);

    try {
        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        log.debug("smtp " + mailSender.getHost());
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail was NOT sent");
        log.error(e);
    }
}

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

@Override
public void sendNotification(String email, ArticleComment comment, Locale locale) throws MailException {

    try {//w  ww  .  j  ava  2 s . co m
        String articleURL = "http://" + domain + "/articles/detail.html?articleId="
                + comment.getArticle().getArticleId();
        //System.out.println(articleURL);
        String subject = messageSource.getMessage("articles.comments.email.subscribtion.subject",
                new String[] { comment.getArticle().getTitle(), comment.getPerson().getUsername() }, locale);
        //System.out.println(subject);
        String emailBody = "<html><body>";

        emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
                new String[] { comment.getArticle().getTitle() }, locale) + "";
        emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL
                + "</a>)</p><br />";
        emailBody += "<h3>Text:</h3> <p>" + comment.getText() + "</p><br />";
        emailBody += "<p>"
                + messageSource.getMessage("articles.group.email.subscribtion.body.text.part2", null, locale)
                + "</p>";
        emailBody += "</body></html>";

        //System.out.println(emailBody);
        log.debug("email body: " + emailBody);

        log.debug("Composing e-mail message");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(mailMessage.getFrom());

        //  message.setContent("text/html");
        message.setTo(email);
        //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
        message.setSubject(subject);
        message.setText(emailBody, true);

        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    } catch (MessagingException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.article.AddArticleController.java

private void sendNotification(String email, Article article, HttpServletRequest request)
        throws MessagingException {
    String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + article.getArticleId();
    //System.out.println(articleURL);
    String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
            new String[] { article.getTitle(), article.getPerson().getUsername() },
            RequestContextUtils.getLocale(request));
    //System.out.println(subject);
    String emailBody = "<html><body>";

    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
            new String[] { article.getTitle() }, RequestContextUtils.getLocale(request)) + "";
    emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />";
    emailBody += "<h3>" + article.getTitle() + "</h3> <p>" + article.getText() + "</p><br />";
    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null,
            RequestContextUtils.getLocale(request)) + "</p>";
    emailBody += "</body></html>";

    //System.out.println(emailBody);
    log.debug("email body: " + emailBody);

    log.debug("Composing e-mail message");
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(mailMessage.getFrom());

    //  message.setContent("text/html");
    message.setTo(email);/*from ww w  . java  2 s  .c  o m*/
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);
    message.setText(emailBody, true);

    try {
        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        log.debug("smtp " + mailSender.getHost());
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail was NOT sent");
        log.error(e);
    }
}

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

@Override
public void sendNotification(String email, Article article, Locale locale) {

    try {/*from  w  w  w  . j  a  v a 2  s  .  com*/
        String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + article.getArticleId();
        // System.out.println(articleURL);
        String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
                new String[] { article.getTitle(), article.getPerson().getUsername() }, locale);
        // System.out.println(subject);
        String emailBody = "<html><body>";

        emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
                new String[] { article.getTitle(),
                        article.getResearchGroup() != null ? article.getResearchGroup().getTitle()
                                : "Public articles" },
                locale) + "";
        emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL
                + "</a>)</p><br />";
        emailBody += "<h3>" + article.getTitle() + "</h3> <p>" + article.getText() + "</p><br />";
        emailBody += "<p>"
                + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null, locale)
                + "</p>";
        emailBody += "</body></html>";

        // System.out.println(emailBody);
        log.debug("email body: " + emailBody);

        log.debug("Composing e-mail message");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(mailMessage.getFrom());

        // message.setContent("text/html");
        message.setTo(email);
        // helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
        message.setSubject(subject);
        message.setText(emailBody, true);

        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");

    } catch (MailException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    } catch (MessagingException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    }
}

From source file:mx.edu.um.mateo.rh.web.JefeSeccionController.java

private void enviaCorreo(String tipo, List<JefeSeccion> jefeSeccions, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;//from   ww  w.ja v a2  s  . c o m
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(jefeSeccions);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(jefeSeccions);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(jefeSeccions);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("jefeSeccion.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}

From source file:mx.edu.um.mateo.rh.web.CategoriaController.java

private void enviaCorreo(String tipo, List<Categoria> categorias, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;/*from w  w w. j ava 2 s  . co  m*/
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(categorias);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(categorias);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(categorias);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("categoria.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}

From source file:edu.unc.lib.dl.services.MailNotifier.java

public void sendIngestSuccessNotice(IngestProperties props, int ingestedCount) {
    String html = null, text = null;
    boolean logEmail = true;
    MimeMessage mimeMessage = null;//w ww. j  a va2 s.  c  o m
    try {
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessText.ftl",
                Locale.getDefault(), "utf-8");

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("numberOfObjects", new Integer(ingestedCount));
        model.put("irBaseUrl", this.irBaseUrl);
        List tops = new ArrayList();
        for (ContainerPlacement p : props.getContainerPlacements().values()) {
            HashMap om = new HashMap();
            om.put("pid", p.pid.getPid());
            om.put("label", p.label);
            tops.add(om);
        }
        model.put("tops", tops);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Success", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    }

    try {
        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        for (String addy : props.getEmailRecipients()) {
            message.addTo(addy);
        }
        message.setSubject("CDR ingest complete");

        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // Document events = new Document(aip.getEventLogger().getAllEvents());
        // message.addAttachment("events.xml", new JDOMStreamSource(events));
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest success email.", e);
    } catch (RuntimeException e) {
        log.error(e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", e);
            }
        }
    }

}

From source file:mx.edu.um.mateo.rh.web.ClaveEmpleadoController.java

private void enviaCorreo(String tipo, List<ClaveEmpleado> claveEmpleados, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;/*  ww w . j  a  v  a 2  s.  co  m*/
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(claveEmpleados);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(claveEmpleados);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(claveEmpleados);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("claveEmpleado.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}

From source file:gr.abiss.calipso.service.EmailService.java

@Async
public void sendEmail(final String subject, final String templateName, String emailTo, String emailFrom,
        final Context ctx) {
    try {//from www. j a  v  a  2s.com
        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(emailFrom);
        message.setTo(emailTo);
        ctx.setVariable("baseUrl", this.baseUrl);
        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process(templateName, ctx);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending email body: " + htmlContent);
        }
        message.setText(htmlContent, true /* isHtml */);

        // Send email
        if (StringUtils.isNotBlank(ConfigurationFactory.getConfiguration().getString("mail.server.host"))) {
            this.mailSender.send(mimeMessage);
        } else {
            LOGGER.warn("Skipped sending email as mail.server.host property is empty");
        }
    } catch (Exception e) {
        LOGGER.error("Failed to send email: ", e);
    }

}

From source file:com.epam.ta.reportportal.util.email.EmailService.java

public void sendConfirmationEmail(CreateUserRQFull req, String basicUrl) {
    MimeMessagePreparator preparator = mimeMessage -> {
        URL logoImg = this.getClass().getClassLoader().getResource(LOGO);
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject("Welcome to Report Portal");
        message.setTo(req.getEmail());//from   w ww.  jav  a 2 s  .  c  om
        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        email.put("url", basicUrl);
        email.put("login", normalizeUsername(req.getLogin()));
        email.put("password", req.getPassword());
        String text = templateEngine.merge("create-user-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(logoImg));
    };
    this.send(preparator);
}