List of usage examples for javax.mail.internet MimeBodyPart getContent
@Override public Object getContent() throws IOException, MessagingException
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private String getBody(MimeMessage msg) throws Exception { MimeBodyPart textPart = getTextPart(msg); return (String) textPart.getContent(); }
From source file:voldemort.coordinator.CoordinatorRestAPITest.java
private TestVersionedValue doGet(String key, Map<String, Object> options) { HttpURLConnection conn = null; String response = null;/*from www .ja v a2 s . c o m*/ TestVersionedValue responseObj = null; int expectedResponseCode = 200; try { // Create the right URL and Http connection String base64Key = new String(Base64.encodeBase64(key.getBytes())); URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key); conn = (HttpURLConnection) url.openConnection(); // Set the right headers conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000"); conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, Long.toString(System.currentTimeMillis())); // options if (options != null) { if (options.get("timeout") != null && options.get("timeout") instanceof String) { conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, (String) options.get("timeout")); } if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) { expectedResponseCode = (Integer) options.get("responseCode"); } } // Check for the right response code if (conn.getResponseCode() != expectedResponseCode) { System.err.println("Illegal response during GET : " + conn.getResponseMessage()); fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode()); } if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) { return null; } // Buffer the result into a string ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); assertEquals("The number of body parts expected is not 1", 1, mp.getCount()); MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0); VectorClock vc = RestUtils .deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]); response = (String) part.getContent(); responseObj = new TestVersionedValue(response, vc); } catch (Exception e) { e.printStackTrace(); fail("Error in sending the REST request"); } finally { if (conn != null) { conn.disconnect(); } } return responseObj; }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestTextAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*from w w w .jav a 2s . c om*/ String attachmentText = "Test Attachment Text"; EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt"); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", textAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart firstAttachment = getFirstAttachment(msg); // check content bytes Object content = firstAttachment.getContent(); assertTrue(content instanceof InputStream); byte[] data = IOUtils.toByteArray((InputStream) content); assertEquals(attachmentText, new String(data, "ISO-8859-1")); // disposition assertEquals(Part.ATTACHMENT, firstAttachment.getDisposition()); // charset header String contentType = firstAttachment.getContentType(); assertTrue(contentType.toLowerCase().contains("charset=iso-8859-1")); }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*from w ww .ja v a 2 s.c o m*/ byte[] pdfBytes = new byte[] { 1, 2, 3, 4, 6 }; String fileName = "invoice.pdf"; EmailAttachment pdfAttach = new EmailAttachment(pdfBytes, fileName); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", pdfAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart attachment = getFirstAttachment(msg); // check content bytes InputStream content = (InputStream) attachment.getContent(); byte[] data = IOUtils.toByteArray(content); assertByteArrayEquals(pdfBytes, data); // disposition assertEquals(Part.ATTACHMENT, attachment.getDisposition()); // mime type String contentType = attachment.getContentType(); assertTrue(contentType.contains("application/pdf")); }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();//w w w . jav a2s . c o m byte[] imageBytes = new byte[] { 1, 2, 3, 4, 5 }; String fileName = "logo.png"; EmailAttachment imageAttach = new EmailAttachment(imageBytes, fileName, "logo"); EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", imageAttach); emailer.sendEmailAsync(myInfo); emailer.processQueuedEmails(); MimeMessage msg = testMailSender.fetchSentEmail(); MimeBodyPart attachment = getInlineAttachment(msg); // check content bytes InputStream content = (InputStream) attachment.getContent(); byte[] data = IOUtils.toByteArray(content); assertByteArrayEquals(imageBytes, data); // disposition assertEquals(Part.INLINE, attachment.getDisposition()); // mime type String contentType = attachment.getContentType(); assertTrue(contentType.contains("image/png")); }
From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java
@Override public void notifyEmailUpdated(String oldAddress, String newAddress) { try {//from ww w . ja v a 2s .c o m //Create the message body final MimeBodyPart msg = new MimeBodyPart(); msg.setContent( "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n" + "New Email Address: " + newAddress + "\n" + "\n" + "If you have any questions, please contact your Human Resources department.", "text/plain"); final MimeMessage message = this.javaMailSender.createMimeMessage(); final Address[] recipients; if (StringUtils.isNotEmpty(oldAddress)) { recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) }; } else { recipients = new Address[] { new InternetAddress(newAddress) }; } message.setRecipients(RecipientType.TO, recipients); message.setFrom(new InternetAddress("payroll@ohr.wisc.edu")); message.setSubject("Business Email Address Change"); // sign the message body if (this.smimeSignedGenerator != null) { final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC"); message.setContent(mm, mm.getContentType()); } // no signing keystore configured, send the message unsigned else { message.setContent(msg.getContent(), msg.getContentType()); } message.saveChanges(); this.javaMailSender.send(message); this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress); } catch (Exception e) { this.logger.error( "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e); } }
From source file:voldemort.restclient.R2Store.java
private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) { Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>(); try {//from w ww. ja v a2 s . c om // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); // Get the outer multipart object ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { // Get an individual part. This contains all the versioned // values for a particular key referenced by content-location MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); // Get the key String contentLocation = part.getHeader("Content-Location")[0]; String base64Key = contentLocation.split("/")[2]; ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key)); if (logger.isDebugEnabled()) { logger.debug("Content-Location : " + contentLocation); logger.debug("Base 64 key : " + base64Key); } // Create an array list for holding all the (versioned values) List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>(); // Get the nested Multi-part object. This contains one part for // each unique versioned value. ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(), "multipart/mixed"); MimeMultipart valueParts = new MimeMultipart(nestedDS); for (int valueId = 0; valueId < valueParts.getCount(); valueId++) { MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId); String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received serialized Vector Clock : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); // get the value bytes InputStream input = valuePart.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock)); } results.put(key, valueResultList); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }
From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java
private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception { MimeBodyPart mbp = (MimeBodyPart) part; String fileName = mbp.getFileName(); String fileType = mbp.getContentType(); String fileId = mbp.getContentID(); String fileEncoding = mbp.getEncoding(); String attContent;//from w w w. ja va2 s . c o m if (fileName == null || fileName.length() < 2) { fileName = new String("Unknown"); if (fileType.indexOf("name") > 0) { int i = fileType.indexOf("name"); int j = fileType.indexOf("\"", i + 1); if (j != -1) { int k = fileType.indexOf("\"", j + 1); if (k != -1) { fileName = fileType.substring(j + 1, k); } } else { int k = fileType.indexOf(";", i + 1); if (k != -1) { fileName = fileType.substring(i + 5, k); } else { fileName = fileType.substring(i + 5, fileType.length()); } } } } InboxAttachment entryItem = new InboxAttachment(); entryItem.setFileName(fileName); if (fileType != null) entryItem.setContentType(fileType); if (mbp.getContent() instanceof InputStream) { InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuffer att = new StringBuffer(); String thisLine = reader.readLine(); while (thisLine != null) { att.append(thisLine); thisLine = reader.readLine(); } attContent = att.toString(); // MimeUtility.encode(part.getOutputStream(), "base64"); // attachments += saveFile(part.getFileName(), part.getInputStream()); } else { attContent = part.getContent().toString(); } entryItem.setContent(attContent); entryItem.setContentId(fileId); inboxentry.addInboxAttachment(entryItem); }
From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above.// w w w. ja v a 2 s . c o m *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { List<String> requiredMetadata = new ArrayList<String>(); for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode sn = spec.getChild(i); if (sn.getType().equals(EmailConfig.NODE_METADATA)) { String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME); requiredMetadata.add(metadataAttribute); } } // Keep a cached set of open folders Map<String, Folder> openFolders = new HashMap<String, Folder>(); try { for (String documentIdentifier : documentIdentifiers) { String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change. // Check if we need to index if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) continue; String compositeID = documentIdentifier; String version = versionString; String folderName = extractFolderNameFromDocumentIdentifier(compositeID); String id = extractEmailIDFromDocumentIdentifier(compositeID); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long startTime = System.currentTimeMillis(); try { try { Folder folder = openFolders.get(folderName); if (folder == null) { getSession(); OpenFolderThread oft = new OpenFolderThread(session, folderName); oft.start(); folder = oft.finishUp(); openFolders.put(folderName, folder); } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'"); SearchTerm messageIDTerm = new MessageIDTerm(id); getSession(); SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm); smt.start(); Message[] message = smt.finishUp(); String msgURL = makeDocumentURI(urlTemplate, folderName, id); Message msg = null; for (Message msg2 : message) { msg = msg2; } if (msg == null) { // email was not found activities.deleteDocument(id); continue; } if (!activities.checkURLIndexable(msgURL)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + msgURL + "')"; activities.noDocument(id, version); continue; } long fileLength = msg.getSize(); if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length (" + fileLength + ")"; activities.noDocument(id, version); continue; } Date sentDate = msg.getSentDate(); if (!activities.checkDateIndexable(sentDate)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + sentDate + ")"; activities.noDocument(id, version); continue; } String mimeType = "text/plain"; if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(id, version); continue; } RepositoryDocument rd = new RepositoryDocument(); rd.setFileName(msg.getFileName()); rd.setMimeType(mimeType); rd.setCreatedDate(sentDate); rd.setModifiedDate(sentDate); String subject = StringUtils.EMPTY; for (String metadata : requiredMetadata) { if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) { Address[] to = msg.getRecipients(Message.RecipientType.TO); String[] toStr = new String[to.length]; int j = 0; for (Address address : to) { toStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, toStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) { Address[] from = msg.getFrom(); String[] fromStr = new String[from.length]; int j = 0; for (Address address : from) { fromStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, fromStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) { subject = msg.getSubject(); rd.addField(EmailConfig.EMAIL_SUBJECT, subject); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) { Multipart mp = (Multipart) msg.getContent(); for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition == null)) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags } } } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) { rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString()); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) { Multipart mp = (Multipart) msg.getContent(); if (mp != null) { String[] encoding = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { encoding[k] = part.getFileName().split("\\?")[1]; } } rd.addField(EmailConfig.ENCODING_FIELD, encoding); } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) { Multipart mp = (Multipart) msg.getContent(); String[] MIMEType = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { MIMEType[k] = part.getContentType(); } } rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType); } } InputStream is = msg.getInputStream(); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(id, version, msgURL, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleMessagingException(e, "processing email"); } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(e, "processing email"); throw new ManifoldCFException(e.getMessage(), e); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong, documentIdentifier, errorCode, errorDesc, null); } } } finally { for (Folder f : openFolders.values()) { try { CloseFolderThread cft = new CloseFolderThread(session, f); cft.start(); cft.finishUp(); } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { handleMessagingException(e, "closing folders"); } } } }
From source file:davmail.imap.ImapConnection.java
protected void appendBodyStructure(StringBuilder buffer, MimeMultipart multiPart) throws IOException, MessagingException { buffer.append('('); for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) multiPart.getBodyPart(i); try {/* www . j a v a2 s. co m*/ Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { appendBodyStructure(buffer, (MimeMultipart) mimeBody); } else { // no multipart, single body appendBodyStructure(buffer, bodyPart); } } catch (UnsupportedEncodingException e) { LOGGER.warn(e); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } catch (MessagingException me) { DavGatewayTray.warn(me); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } } int slashIndex = multiPart.getContentType().indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType()); } int semiColonIndex = multiPart.getContentType().indexOf(';'); if (semiColonIndex < 0) { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1).toUpperCase()) .append("\")"); } else { buffer.append(" \"").append( multiPart.getContentType().substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()) .append("\")"); } }