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:gr.abiss.calipso.service.EmailService.java

@Async
public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from www  . jav  a2 s  .com

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    LOGGER.info("Sending email body: " + htmlContent);
    message.setText(htmlContent, true /* isHtml */);

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

}

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

@Async
public void sendMailWithInline(final String recipientName, final String recipientEmail,
        final String imageResourceName, final byte[] imageBytes, final String imageContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with inline image");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from   www .j av a2  s.  c om

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx);
    LOGGER.info("Sending email body: " + htmlContent);
    message.setText(htmlContent, true /* isHtml */);

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
    message.addInline(imageResourceName, imageSource, imageContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("diaFeriado.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:com.github.dactiv.fear.service.service.message.MessageService.java

/**
 * ??//from   w w  w. jav  a 2s  .c o m
 *
 * @param nickname ?? null
 * @param mail     
 */
private void doSendMail(String nickname, Mail mail) {
    try {

        JavaMailSender mailSender = getJavaMailSender();

        if (mailSender == null) {
            throw new ServiceException("???");
        }

        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper;

        if (mailSender instanceof JavaMailSenderImpl) {
            JavaMailSenderImpl jmsi = (JavaMailSenderImpl) mailSender;
            helper = new MimeMessageHelper(msg, true, jmsi.getDefaultEncoding());
        } else {
            helper = new MimeMessageHelper(msg, true);
        }

        helper.setTo(mail.getTo());
        helper.setFrom(getSendForm(nickname, mailSender));
        helper.setSubject(mail.getTitle());
        helper.setText(mail.getContent(), mail.getHtml());

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

        mailSender.send(msg);

        LOGGER.info("???");
    } catch (Exception e) {
        LOGGER.error("??", e);
    }
}

From source file:ch.javaee.basicMvc.service.MailSenderService.java

@Async
public void sendAuthorizationMail(final User user, final SecurityCode securityCode) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setSubject(mailBean.getSubject());
            message.setTo(user.getEmail());
            message.setFrom(mailBean.getFrom());
            Map model = new HashMap();
            model.put("websiteName", mailBean.getWebsiteName());
            model.put("host", mailBean.getHost());
            model.put("user", user);
            model.put("securityCode", securityCode);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, CONFIRMATION_TEMPLATE,
                    model);/*from   w  ww  .  j a  v a 2s  . com*/
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("jefe.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:eu.trentorise.smartcampus.citizenportal.service.EmailService.java

public String sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String practice_id, final String position, final String score, final String phase,
        final String ef_period, final String ef_category, final String ef_tool, final String subject,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("practice_id", practice_id);
    ctx.setVariable("position", position);
    ctx.setVariable("score", score);
    ctx.setVariable("phase", phase);
    ctx.setVariable("ef_period", ef_period);
    ctx.setVariable("ef_category", ef_category);
    ctx.setVariable("ef_tool", ef_tool);
    ctx.setVariable("subscriptionDate", new Date());
    //ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    ctx.setVariable("text", subject);

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Graduatoria Edilizia Abitativa");
    //message.setFrom("thymeleaf@example.com");
    message.setFrom("myweb.edilizia@comunitadellavallagarina.tn.it");
    message.setTo(recipientEmail);/*from   w  ww  .  j  a v a  2  s  . c  o  m*/

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    message.setText(htmlContent, true /* isHtml */);

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

    return recipientName + "OK";
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("vacaciones.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:org.toobsframework.email.SmtpMailSender.java

public void sendEmail(EmailBean email) throws MailException, MessagingException {
    JavaMailSender javaMailSender = (JavaMailSender) javaMailSenders.get(email.getMailSenderKey());
    if (javaMailSender == null) {
        throw new MessagingException(email.getMailSenderKey() + " is an invalid mailSenderKey");
    }//w  w  w.j a  v a  2s  . c om
    if (this.getMailProperties() != null) {
        ((JavaMailSenderImpl) javaMailSender).setJavaMailProperties(this.getMailProperties());
    }
    try {
        String[] recipients = this.processRecipients(email.getRecipients());
        String[] bccs = new String[email.getBccs().size()];
        for (int i = 0; i < recipients.length; i++) {
            MimeMessage message = null;
            MimeMessageHelper helper = null;
            String thisRecipient = recipients[i];
            switch (email.getType()) {
            case EmailBean.MESSAGE_TYPE_TEXT:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, false, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), false);
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            case EmailBean.MESSAGE_TYPE_HTML:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, true, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), email.getMessageHtml());
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            }
        }
    } catch (Exception e) {
        log.error("Mail exception " + e.getMessage(), e);
        throw new MessagingException(e.getMessage());
    }
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("vacacionesEmpleado.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);
}