List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(String data, String type) throws IOException
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 w ww . j a 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:com.xebialabs.xlt.ci.server.XLTestServerImplTest.java
private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException { assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1"); assertEquals(request.getHeader("accept"), "application/json; charset=utf-8"); assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4="); assertThat(request.getHeader("Content-Length"), is(nullValue())); assertThat(request.getHeader("Transfer-Encoding"), is("chunked")); assertThat(request.getChunkSizes().get(0), greaterThan(0)); assertThat(request.getChunkSizes().size(), greaterThan(0)); assertTrue(request.getBodySize() > 0); ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(bads); assertTrue(request.getBodySize() > 0); assertEquals(mp.getCount(), 2);//w w w. j a v a 2 s. c o m assertEquals(mp.getContentType(), "multipart/mixed"); // TODO could do additional checks on metadata content BodyPart bodyPart1 = mp.getBodyPart(0); assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8"); BodyPart bodyPart2 = mp.getBodyPart(1); assertEquals(bodyPart2.getContentType(), "application/zip"); }
From source file:org.kuali.coeus.propdev.impl.s2s.S2sSubmissionServiceImpl.java
/** * This method is used to submit forms to Grants.gov. It generates forms for * a given {@link ProposalDevelopmentDocument}, validates and then submits * the forms/*w ww .j a v a 2 s . c o m*/ * * @param pdDoc * Proposal Development Document. * @return true if submitted false otherwise. * @throws S2sCommunicationException */ public FormGenerationResult submitApplication(ProposalDevelopmentDocument pdDoc) throws S2sCommunicationException { final FormGenerationResult result = s2SService.generateAndValidateForms(pdDoc); if (result.isValid()) { Map<String, DataHandler> attachments = new HashMap<String, DataHandler>(); List<S2sAppAttachments> s2sAppAttachmentList = new ArrayList<S2sAppAttachments>(); DataHandler attachmentFile; for (AttachmentData attachmentData : result.getAttachments()) { attachmentFile = new DataHandler( new ByteArrayDataSource(attachmentData.getContent(), attachmentData.getContentType())); attachments.put(attachmentData.getContentId(), attachmentFile); S2sAppAttachments appAttachments = new S2sAppAttachments(); appAttachments.setContentId(attachmentData.getContentId()); appAttachments.setProposalNumber(pdDoc.getDevelopmentProposal().getProposalNumber()); s2sAppAttachmentList.add(appAttachments); } S2sAppSubmission appSubmission = new S2sAppSubmission(); appSubmission.setStatus(S2sAppSubmissionConstants.GRANTS_GOV_STATUS_MESSAGE); appSubmission.setComments(S2sAppSubmissionConstants.GRANTS_GOV_COMMENTS_MESSAGE); SubmitApplicationResponse response = null; S2sOpportunity s2sOpportunity = pdDoc.getDevelopmentProposal().getS2sOpportunity(); S2SConnectorService connectorService = getS2sConnectorService(s2sOpportunity); response = connectorService.submitApplication(result.getApplicationXml(), attachments, pdDoc.getDevelopmentProposal().getProposalNumber()); appSubmission.setStatus(S2sAppSubmissionConstants.GRANTS_GOV_SUBMISSION_MESSAGE); saveSubmissionDetails(pdDoc, appSubmission, response, result.getApplicationXml(), s2sAppAttachmentList); result.setValid(true); } return result; }
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. 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:mx.edu.um.mateo.general.web.BaseController.java
protected void enviaCorreo(String tipo, List<?> lista, HttpServletRequest request, String nombre, String tipoReporte, Long id) throws ReporteException { try {/*from w w w .j a v a 2 s. c o m*/ log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null; switch (tipo) { case "PDF": archivo = generaPdf(lista, nombre, tipoReporte, id); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(lista, nombre, tipoReporte, id); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(lista, nombre, tipoReporte, id); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getCorreo()); String titulo = messageSource.getMessage(nombre + ".reporte.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); } catch (JRException | MessagingException e) { throw new ReporteException("No se pudo generar el reporte", e); } }
From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java
/** * First we clean the eHealthBox. Then we publish to ourself. Next we * download this message.//from www. ja va 2s . c om * * @throws Exception */ @Test public void testScenarioInvoke() throws Exception { // STS EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox: remove all messages. EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient( "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3"); eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString); GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); eHealthBoxClient.deleteMessage(messageId); } // eHealthBox: publish via SOAP attachment EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("application/octet-stream"); publicationDocument.setDownloadFileName("test.dat"); byte[] data = new byte[1024 * 256]; DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream"); DataHandler dataHandler = new DataHandler(dataSource); publicationDocument.setEncryptableBinaryContent(dataHandler); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(data); publicationDocument.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); // give eHealthBox some time. Thread.sleep(1000 * 5); LOG.debug("GET MESSAGES LIST"); messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); LOG.debug("GET FULL MESSAGE"); String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">" + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>" + "</ehbox:GetFullMessageRequest>"; String response = eHealthBoxClient.invoke(request); LOG.debug("RESPONSE: " + response); JAXBContext consultationContext = JAXBContext .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class); Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller(); Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments(); consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments)); JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller .unmarshal(new StringReader(response)); GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue(); ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage(); be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage .getContentContext(); ConsultationContentType consultationContent = consultationContentContext.getContent(); ConsultationDocumentType consultationDocument = consultationContent.getDocument(); byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent(); if (null != encryptableTextContent) { LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length); } else { LOG.debug("no EncryptableTextContent"); } DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent(); if (null != resultDataHandler) { LOG.debug("result EncryptableBinaryContent"); byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream()); LOG.debug("result data size: " + resultData.length); } LOG.debug("DELETE MESSAGE"); eHealthBoxClient.deleteMessage(messageId); } }
From source file:mx.edu.um.mateo.rh.web.EstudiosEmpleadoController.java
private void enviaCorreo(String tipo, List<EstudiosEmpleado> estudiosEmpleados, HttpServletRequest request) throws JRException, MessagingException { log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null;//ww w. j ava2 s .c o m switch (tipo) { case "PDF": archivo = generaPdf(estudiosEmpleados); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(estudiosEmpleados); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(estudiosEmpleados); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getUsername()); String titulo = messageSource.getMessage("estudiosEmpleado.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:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java
/** * First we clean the eHealthBox. Then we publish to ourself. Next we * download this message.//from w w w . jav a2s . co m * * @throws Exception */ @Test public void testScenarioInvoke() throws Exception { // STS EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox: remove all messages. EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient( "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3"); eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString); GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); eHealthBoxClient.deleteMessage(messageId); } // eHealthBox: publish via SOAP attachment EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("application/octet-stream"); publicationDocument.setDownloadFileName("test.dat"); byte[] data = new byte[1024 * 256]; for (int idx = 0; idx < data.length; idx++) { data[idx] = 'X'; } DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream"); DataHandler dataHandler = new DataHandler(dataSource); publicationDocument.setEncryptableBinaryContent(dataHandler); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(data); publicationDocument.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); // give eHealthBox some time. Thread.sleep(1000 * 5); LOG.debug("GET MESSAGES LIST"); messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); LOG.debug("GET FULL MESSAGE"); String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">" + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>" + "</ehbox:GetFullMessageRequest>"; String response = eHealthBoxClient.invoke(request); LOG.debug("RESPONSE: " + response); JAXBContext consultationContext = JAXBContext .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class); Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller(); Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments(); for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) { LOG.debug("message attachment id: " + messageAttachment.getKey()); LOG.debug("message data handler: " + messageAttachment.getValue()); DataHandler resultDataHandler = messageAttachment.getValue(); DataSource resultDataSource = resultDataHandler.getDataSource(); byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream()); LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length); } consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments)); JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller .unmarshal(new StringReader(response)); GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue(); ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage(); be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage .getContentContext(); ConsultationContentType consultationContent = consultationContentContext.getContent(); ConsultationDocumentType consultationDocument = consultationContent.getDocument(); byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent(); if (null != encryptableTextContent) { LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length); } else { LOG.debug("no EncryptableTextContent"); } DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent(); if (null != resultDataHandler) { LOG.debug("result EncryptableBinaryContent"); byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream()); LOG.debug("result data size: " + resultData.length); } LOG.debug("DELETE MESSAGE"); eHealthBoxClient.deleteMessage(messageId); } }
From source file:mitm.common.pdf.MessagePDFBuilder.java
private Part convertRFC822(Part attachment) { try {/*from w w w . ja v a2 s . c o m*/ Object o = attachment.getContent(); if (o instanceof MimeMessage) { MimeMessage message = (MimeMessage) o; MessagePDFBuilder pdfBuilder = this.clone(); ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); pdfBuilder.buildPDF(message, null, pdfStream); MimePart pdfPart = new MimeBodyPart(); pdfPart.setDataHandler( new DataHandler(new ByteArrayDataSource(pdfStream.toByteArray(), "application/pdf"))); String filename = getFilename(attachment, "message.pdf"); if (!filename.toLowerCase().endsWith(".pdf")) { filename = filename + ".pdf"; } pdfPart.setFileName(filename); return pdfPart; } } catch (IOException e) { logger.error("Error trying to converting to RFC822."); } catch (MessagingException e) { logger.error("Error trying to converting to RFC822."); } catch (DocumentException e) { logger.error("Error trying to converting to RFC822."); } return attachment; }