Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java

@Override
public boolean send(final EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }//from   w  w w.  j  a  va2s  .  c  o  m

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            if (CollectionUtils.isNotEmpty(toAddresses)) {
                email.setTo(getAddresses(toAddresses));
            } else {
                throw new IllegalArgumentException("message has no To addresses");
            }

            final List<EmailAddressModel> ccAddresses = message.getCcAddresses();
            if (ccAddresses != null && !ccAddresses.isEmpty()) {
                email.setCc(getAddresses(ccAddresses));
            }

            final List<EmailAddressModel> bccAddresses = message.getBccAddresses();
            if (bccAddresses != null && !bccAddresses.isEmpty()) {
                email.setBcc(getAddresses(bccAddresses));
            }

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));

            // Add the reply to if specified
            final String replyToAddress = message.getReplyToAddress();
            if (replyToAddress != null && !replyToAddress.isEmpty()) {
                email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null)));
            }

            email.setSubject(message.getSubject());
            email.setHtmlMsg(getBody(message));

            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (attachments != null && !attachments.isEmpty()) {
                for (final EmailAttachmentModel attachment : attachments) {
                    try {
                        final DataSource dataSource = new ByteArrayDataSource(
                                getMediaService().getDataFromMedia(attachment), attachment.getMime());
                        email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText());
                    } catch (final EmailException ex) {
                        LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex);
                        return false;
                    }
                }
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject()
                    + "] cause: " + e.getMessage());
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message buildMail(Session session) throws MessagingException, IOException {
    String subject = createSubject();
    Message mimeMessage = createMimeMessage(session, subject);
    mimeMessage.setDisposition(MimeMessage.INLINE);
    Multipart mp = new MimeMultipart("alternative");

    MimeBodyPart textBp = new MimeBodyPart();
    textBp.setDisposition(MimeMessage.INLINE);
    textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8");
    mp.addBodyPart(textBp);// w ww  .  ja v a 2s . c om

    Multipart commentMultipart = null;
    EmailDto dto = model.getObject();
    if (StringUtils.isNotEmpty(dto.getBody())) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(MimeMessage.INLINE);
        DataHandler dataHandler = new DataHandler(
                new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8"));
        bodyPart.setDataHandler(dataHandler);

        commentMultipart = new MimeMultipart("mixed");
        commentMultipart.addBodyPart(bodyPart);
    }

    String html = createHtml();
    Multipart htmlMp = createHtmlPart(html);

    BodyPart htmlBp = new MimeBodyPart();
    htmlBp.setDisposition(BodyPart.INLINE);
    htmlBp.setContent(htmlMp);
    if (commentMultipart == null) {
        mp.addBodyPart(htmlBp);
    } else {
        commentMultipart.addBodyPart(htmlBp);
        BodyPart all = new MimeBodyPart();
        all.setDisposition(BodyPart.INLINE);
        all.setContent(commentMultipart);
        mp.addBodyPart(all);
    }
    mimeMessage.setContent(mp);

    return mimeMessage;
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /* w w w.j  a  va 2s .c  om*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @param responseBody//  w  w w.  jav a  2  s.  c o m
 * @throws MessagingException
 */
private Document handleMultipart(byte[] responseBody, String contentType) throws Exception {
    ByteArrayDataSource bads = new ByteArrayDataSource(responseBody, contentType);
    MimeMultipart multipart = new MimeMultipart(bads);
    XMLUtils xml = XMLUtils.getParserInstance();
    Document doc = null;
    try {
        doc = xml.newDocument("MultipartHttpResponse");
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
    for (int i = 0; i < multipart.getCount(); i++) {
        dumpPart(multipart.getBodyPart(i), doc.getDocumentElement(), doc);
    }
    return doc;
}

From source file:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static EbMSMessage ebMSMessageContentToEbMSMessage(CollaborationProtocolAgreement cpa,
        EbMSMessageContent content, String hostname) throws DatatypeConfigurationException {
    MessageHeader messageHeader = createMessageHeader(cpa, content.getContext(), hostname);

    AckRequested ackRequested = createAckRequested(cpa, content.getContext());

    Manifest manifest = createManifest();
    for (int i = 0; i < content.getAttachments().size(); i++)
        manifest.getReference().add(createReference(i + 1));

    List<DataSource> attachments = new ArrayList<DataSource>();
    for (EbMSAttachment attachment : content.getAttachments()) {
        ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
        ds.setName(attachment.getName());
        attachments.add(ds);//from   w w w  . j  av a 2s .co m
    }

    return new EbMSMessage(messageHeader, ackRequested, manifest, attachments);
}

From source file:org.jembi.rhea.transformers.XDSRepositoryProvideAndRegisterDocument.java

protected ProvideAndRegisterDocumentSetRequestType buildRegisterRequest(String oru_r01_request,
        EncounterInfo enc, XDSAffinityDomain domain) {
    ProvideAndRegisterDocumentSetRequestType xdsRequest = new ProvideAndRegisterDocumentSetRequestType();
    SubmitObjectsRequest submissionRequest = new SubmitObjectsRequest();
    RegistryObjectListType registryObjects = new RegistryObjectListType();
    submissionRequest.setRegistryObjectList(registryObjects);
    xdsRequest.setSubmitObjectsRequest(submissionRequest);
    Date now = new Date();

    // For each document
    ExtrinsicObjectType document = XDSUtil.createExtrinsicObject("text/xml", "Physical",
            XdsGuidType.XDSDocumentEntry);

    // To add slots
    document.getSlot().add(XDSUtil.createSlot("creationTime", formatter_yyyyMMdd.format(now)));
    document.getSlot().add(XDSUtil.createSlot("languageCode", "en-us"));
    document.getSlot().add(XDSUtil.createSlot("serviceStartTime", enc.getEncounterDateTime()));
    document.getSlot().add(XDSUtil.createSlot("serviceStopTime", enc.getEncounterDateTime()));
    document.getSlot().add(XDSUtil.createSlot("sourcePatientId", enc.getPID()));
    document.getSlot()//from  w w  w  .  j a  v a  2s.  co  m
            .add(XDSUtil.createSlot("sourcePatientInfo", "PID-3|" + enc.getPID(), "PID-5|" + enc.getName()));
    //if (domain.getRepositoryUniqueId()!=null)
    //   document.getSlot().add(XDSUtil.createSlot("repositoryUniqueId", domain.getRepositoryUniqueId()));
    //if (domain.getHomeCommunityId()!=null)
    //   document.getSlot().add(XDSUtil.createSlot("homeCommunityId", domain.getHomeCommunityId()));

    // To add classifications
    SlotType1[] authorSlots = new SlotType1[] { XDSUtil.createSlot("authorPerson", enc.getAttendingDoctor()),
            XDSUtil.createSlot("authorInstitution", enc.getLocation()), };
    document.getClassification().add(
            XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_Author, "", null, authorSlots));

    SlotType1[] classCodeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getClassCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_ClassCode,
                    domain.getClassCode().getCode(), domain.getClassCode().getDisplay(), classCodeSlots));

    SlotType1[] confidentialitySlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getConfidentialityCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_ConfidentialityCode,
                    domain.getConfidentialityCode().getCode(), domain.getConfidentialityCode().getDisplay(),
                    confidentialitySlots));

    // To add external ids
    document.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSDocumentEntry_PatientId, enc.getPID()));
    String docUniqueId = String.format("%s.%s.%s", systemSourceID, "1",
            new SimpleDateFormat("yyyy.MM.dd.ss.SSS").format(now));
    document.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSDocumentEntry_UniqueId, docUniqueId));

    // Add to list of objects
    registryObjects.getIdentifiable()
            .add(new JAXBElement<ExtrinsicObjectType>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "ExtrinsicObject"),
                    ExtrinsicObjectType.class, document));

    //TODO eventCodeList

    // Create submission set
    RegistryPackageType pkg = XDSUtil.createRegistryPackage();
    pkg.getSlot().add(XDSUtil.createSlot("submissionTime", formatter_yyyyMMdd.format(now)));

    // To add classifications
    SlotType1[] contentTypeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getContentTypeCode().getCodingScheme()) };
    pkg.getClassification().add(XDSUtil.createClassification(pkg, XdsGuidType.XDSSubmissionSet_ContentType,
            domain.getContentTypeCode().getCode(), domain.getContentTypeCode().getDisplay(), contentTypeSlots));

    SlotType1[] formatSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getFormatCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_FormatCode,
                    domain.getFormatCode().getCode(), domain.getFormatCode().getDisplay(), formatSlots));

    SlotType1[] healthcareFacilityTypeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getHealthcareFacilityTypeCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_HealthcareFacilityCode,
                    domain.getHealthcareFacilityTypeCode().getCode(),
                    domain.getHealthcareFacilityTypeCode().getDisplay(), healthcareFacilityTypeSlots));

    SlotType1[] practiceSettingSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getPracticeSettingCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_PracticeSettingCode,
                    domain.getPracticeSettingCode().getCode(), domain.getPracticeSettingCode().getDisplay(),
                    practiceSettingSlots));

    SlotType1[] typeSlots = new SlotType1[] {
            XDSUtil.createSlot("codingScheme", domain.getTypeCode().getCodingScheme()) };
    document.getClassification()
            .add(XDSUtil.createClassification(document, XdsGuidType.XDSDocumentEntry_TypeCode,
                    domain.getTypeCode().getCode(), domain.getTypeCode().getDisplay(), typeSlots));

    // To add external ids
    pkg.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_PatientId, enc.getPID()));
    _uniqueId = String.format("%s.%s.%s", systemSourceID, "2",
            new SimpleDateFormat("yyyy.MM.dd.ss.SSS").format(now));
    pkg.getExternalIdentifier()
            .add(XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_UniqueId, _uniqueId));
    pkg.getExternalIdentifier().add(
            XDSUtil.createExternalIdentifier(document, XdsGuidType.XDSSubmissionSet_SourceId, systemSourceID));

    // Add package to submission
    registryObjects.getIdentifiable()
            .add(new JAXBElement<RegistryPackageType>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "RegistryPackage"),
                    RegistryPackageType.class, pkg));

    // Add classification for state
    registryObjects.getIdentifiable().add(new JAXBElement<ClassificationType>(
            new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Classification"),
            ClassificationType.class, XDSUtil.createNodeClassification(pkg, XdsGuidType.XDSSubmissionSet)));

    // Add association
    registryObjects.getIdentifiable()
            .add(new JAXBElement<AssociationType1>(
                    new QName("urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Association"),
                    AssociationType1.class, XDSUtil.createAssociation(pkg, document, "Original",
                            "urn:oasis:names:tc:ebxml-regrep:AssociationType:HasMember")));

    // Add document
    Document content = new Document();
    content.setId(document.getId());
    content.setValue(
            new DataHandler(new ByteArrayDataSource(oru_r01_request.getBytes(), "application/octet-stream")));
    xdsRequest.getDocument().add(content);

    return xdsRequest;
}

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 ww  w. j a  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:com.zimbra.cs.mime.Mime.java

/**
 * Some devices send wide base64 encoded message body i.e. without line folding.
 * As per RFC https://www.ietf.org/rfc/rfc2045.txt see 6.8.  Base64 Content-Transfer-Encoding
 * "The encoded output stream must be represented in lines of no more than 76 characters each."
 * //w w w . j  ava2  s .  c  o  m
 * To fix the issue here, re-writing the same content to message part.
 * @param mm
 * @throws MessagingException
 * @throws IOException
 */
public static void fixBase64MimePartLineFolding(MimeMessage mm) throws MessagingException, IOException {
    List<MPartInfo> mList = Mime.getParts(mm);
    for (MPartInfo mPartInfo : mList) {
        String ct = mPartInfo.getMimePart().getHeader("Content-Transfer-Encoding", ":");
        if (MimeConstants.ET_BASE64.equalsIgnoreCase(ct)) {
            InputStream io = mPartInfo.getMimePart().getInputStream();
            String ctype = mPartInfo.getMimePart().getContentType();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(io, bos);
            DataSource ds = new ByteArrayDataSource(bos.toByteArray(), ctype);
            DataHandler dh = new DataHandler(ds);
            mPartInfo.getMimePart().setDataHandler(dh);
            mPartInfo.getMimePart().setHeader("Content-Transfer-Encoding", ct);
            mPartInfo.getMimePart().setHeader("Content-Type", ctype);
        }
    }
}

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  .  j  a v a2  s .  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:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(attachment.getName());
    if (StringUtils.isNotBlank(attachment.getDescription())) {
        attachmentPart.setDescription(attachment.getDescription());
    }/* w  w  w.j  av  a2 s .co m*/
    if (StringUtils.isNotBlank(attachment.getDisposition())) {
        attachmentPart.setDisposition(attachment.getDisposition());
    }
    DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType());
    attachmentPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentPart);
}