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

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

Introduction

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

Prototype

public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
        throws MessagingException 

Source Link

Document

Add an attachment to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource .

Usage

From source file:com.miserablemind.butter.domain.service.email.EmailService.java

/**
 * Sends a mime mail with a specified Velocity template that may contain HTML and attachments.
 *
 * @param emailMessage prepared message object to be sent. Usually prepared by {@link EmailManager}
 *//* w  w  w . j a  v  a  2  s . com*/
public void sendMimeMail(final EmailMessage emailMessage) {

    MimeMessagePreparator preparedMessage = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.setTo(emailMessage.getToEmail());
            message.setFrom(emailMessage.getFromAddress());
            message.setReplyTo(emailMessage.getFromAddress());
            message.setSubject(emailMessage.getSubject());
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    emailMessage.getTemplatePath(), "UTF-8", emailMessage.getModel());

            message.setText(body, true);

            if (!StringUtils.isBlank(emailMessage.getAttachmentPath())) {
                FileSystemResource file = new FileSystemResource(emailMessage.getAttachmentPath());
                message.addAttachment(emailMessage.getAttachmentName(), file);
            }
        }
    };

    try {
        this.mailSender.send(preparedMessage);
    } catch (MailException e) {
        logger.error("Email Service Exception Send Mime Mail: " + e.getMessage(), e);
    }

}

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 ww  . ja v  a  2  s  .  c o 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: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;/*from  w w  w  .  ja va  2s  . c  o  m*/
    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: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 va2s.  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: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;/*from w  ww.  j  a v  a 2 s . co 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);
}

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;/* ww  w  .  j av  a  2  s  .c om*/
    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;/*www . ja  v  a  2s .c o  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: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;/*from w  ww  .ja va 2 s.c om*/
    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:it.jugpadova.blo.ParticipantBo.java

/**
 * General participant mail sender/*from   w  ww .  j  a va2s . c  o m*/
 *
 * @param participant
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Participant participant, final String baseUrl, final String subject,
        final String template, final Resource attachment, final String attachmentName) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("baseUrl", baseUrl);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
            if (attachment != null) {
                message.addAttachment(attachmentName, attachment);
            }
        }
    };
    this.mailSender.send(preparator);
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email./*from   w ww .  j  a va 2s  .  co  m*/
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}