javax.mail.Part Java Examples
The following examples show how to use
javax.mail.Part.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: cfMailMessageData.java From openbd-core with GNU General Public License v3.0 | 7 votes |
public static String getFilename( Part Mess ) throws MessagingException{ // Part.getFileName() doesn't take into account any encoding that may have been // applied to the filename so in order to obtain the correct filename we // need to retrieve it from the Content-Disposition String [] contentType = Mess.getHeader( "Content-Disposition" ); if ( contentType != null && contentType.length > 0 ){ int nameStartIndx = contentType[0].indexOf( "filename=\"" ); if ( nameStartIndx != -1 ){ String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) ); try { filename = MimeUtility.decodeText( filename ); return filename; } catch (UnsupportedEncodingException e) {} } } // couldn't determine it using the above, so fall back to more reliable but // less correct option return Mess.getFileName(); }
Example #2
Source File: SubethaEmailMessage.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
private void addBody(Part messagePart) throws MessagingException { if (body != null) { attachmentList.add(new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject() + " (part " + ++bodyNumber + ")", messagePart))); if (log.isInfoEnabled()) { log.info(String.format("Attachment \"%s\" has been added.", attachmentList.get(attachmentList.size() - 1).getFileName())); } } else { body = new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject(), messagePart)); if (log.isDebugEnabled()) { log.debug("Body has been added."); } } }
Example #3
Source File: EmailSender.java From cuba with Apache License 2.0 | 6 votes |
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException { DataSource source = new MyByteArrayDataSource(attachment.getContent()); String mimeType = FileTypesHelper.getMIMEType(attachment.getName()); String contentId = attachment.getContentId(); if (contentId == null) { contentId = generateAttachmentContentId(attachment.getName()); } String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE; String charset = MimeUtility.mimeCharset(attachment.getEncoding() != null ? attachment.getEncoding() : StandardCharsets.UTF_8.name()); String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, attachment.getName()); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setHeader("Content-ID", "<" + contentId + ">"); attachmentPart.setHeader("Content-Type", contentTypeValue); attachmentPart.setFileName(attachment.getName()); attachmentPart.setDisposition(disposition); return attachmentPart; }
Example #4
Source File: MimePackage.java From ats-framework with Apache License 2.0 | 6 votes |
/** * Check if the body is from the content type and returns it if not attachment * * @param mimePart * @param contentType * @return null if not with specific content type or part is attachment */ private String getBodyIfNotAttachment( BodyPart mimePart, String contentType ) throws MessagingException, IOException { String mimePartContentType = mimePart.getContentType().toLowerCase(); if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type String contentDisposition = mimePart.getDisposition(); if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) { Object partContent = mimePart.getContent(); if (partContent instanceof InputStream) { return IoUtils.streamToString((InputStream) partContent); } else { return partContent.toString(); } } } return null; }
Example #5
Source File: MailReader.java From development with Apache License 2.0 | 6 votes |
/** * Get the content of a mail message. * * @param message * the mail message * @return the content of the mail message */ private String getMessageContent(Message message) throws MessagingException { try { Object content = message.getContent(); if (content instanceof Multipart) { StringBuffer messageContent = new StringBuffer(); Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { Part part = multipart.getBodyPart(i); if (part.isMimeType("text/plain")) { messageContent.append(part.getContent().toString()); } } return messageContent.toString(); } return content.toString(); } catch (IOException e) { e.printStackTrace(); } return ""; }
Example #6
Source File: EmailReader.java From baleen with Apache License 2.0 | 6 votes |
private String getContent(Message msg) throws IOException, MessagingException { Object messageContentObject = msg.getContent(); if (messageContentObject instanceof Multipart) { Multipart multipart = (Multipart) msg.getContent(); // Loop over the parts of the email for (int i = 0; i < multipart.getCount(); i++) { // Retrieve the next part Part part = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) && StringUtils.isBlank(part.getFileName())) { return part.getContent().toString(); } } } else { return msg.getContent().toString().trim(); } return ""; }
Example #7
Source File: EmailReader.java From baleen with Apache License 2.0 | 6 votes |
private List<String> getAttachments(Message msg) throws MessagingException, IOException { Object messageContentObject = msg.getContent(); List<String> attachments = new ArrayList<>(); if (messageContentObject instanceof Multipart) { Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { Part part = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) && StringUtils.isBlank(part.getFileName())) { continue; } attachments.add(part.getFileName()); } } return attachments; }
Example #8
Source File: EMLTransformer.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Find "text" parts of message recursively and appends it to sb StringBuilder * * @param multipart Multipart to process * @param sb StringBuilder * @throws MessagingException * @throws IOException */ private void processMultiPart(Multipart multipart, StringBuilder sb) throws MessagingException, IOException { boolean isAlternativeMultipart = multipart.getContentType().contains(MimetypeMap.MIMETYPE_MULTIPART_ALTERNATIVE); if (isAlternativeMultipart) { processAlternativeMultipart(multipart, sb); } else { for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); if (part.getContent() instanceof Multipart) { processMultiPart((Multipart) part.getContent(), sb); } else { processPart(part, sb); } } } }
Example #9
Source File: ServiceMcaCondition.java From scipio-erp with Apache License 2.0 | 6 votes |
private List<String> getBodyText(Part part) throws MessagingException, IOException { Object c = part.getContent(); if (c instanceof String) { return UtilMisc.toList((String) c); } else if (c instanceof Multipart) { List<String> textContent = new ArrayList<>(); // SCIPIO: switched to ArrayList int count = ((Multipart) c).getCount(); for (int i = 0; i < count; i++) { BodyPart bp = ((Multipart) c).getBodyPart(i); textContent.addAll(this.getBodyText(bp)); } return textContent; } else { return new ArrayList<>(); // SCIPIO: switched to ArrayList } }
Example #10
Source File: BlueDragonMailWrapper.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public cfArrayData getBodyParts(){ try{ cfArrayData arr = cfArrayData.createArray( 1 ); if ( message.isMimeType("multipart/*") ){ Multipart mp = (Multipart)message.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) arr.addElement( new BlueDragonPartWrapper(mp.getBodyPart(i)) ); }else{ arr.addElement( new BlueDragonPartWrapper( (Part)message ) ); } return arr; }catch(Exception e){ return cfArrayData.createArray( 1 ); } }
Example #11
Source File: AbstractTransport.java From javamail with Apache License 2.0 | 6 votes |
/** * Recursive find body parts and save them to HashMap */ private static void checkPartForTextType(HashMap<String, Collection<String>> bodies, Part part) throws IOException, MessagingException { Object content = part.getContent(); if (content instanceof CharSequence) { String ct = part.getContentType(); Collection<String> value = bodies.get(ct); if (value != null) { value.add(content.toString()); } else { value = new LinkedList<>(); value.add(content.toString()); bodies.put(ct, value); } } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for(int i = 0; i < mp.getCount(); i++) { checkPartForTextType(bodies, mp.getBodyPart(i)); } } }
Example #12
Source File: MimeMessageParser.java From eml-to-pdf-converter with Apache License 2.0 | 6 votes |
/** * Get the String Content of a MimePart. * @param p MimePart * @return Content as String * @throws IOException * @throws MessagingException */ private static String getStringContent(Part p) throws IOException, MessagingException { Object content = null; try { content = p.getContent(); } catch (Exception e) { Logger.debug("Email body could not be read automatically (%s), we try to read it anyway.", e.toString()); // most likely the specified charset could not be found content = p.getInputStream(); } String stringContent = null; if (content instanceof String) { stringContent = (String) content; } else if (content instanceof InputStream) { stringContent = new String(ByteStreams.toByteArray((InputStream) content), "utf-8"); } return stringContent; }
Example #13
Source File: MailUtils.java From scada with MIT License | 6 votes |
/** * ����ʼ��ı����� * @param part �ʼ��� * @param content �洢�ʼ��ı����ݵ��ַ��� */ public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { //������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж� boolean isContainTextAttach = part.getContentType().indexOf("name") > 0; if (part.isMimeType("text/*") && !isContainTextAttach) { content.append(part.getContent().toString()); } else if (part.isMimeType("message/rfc822")) { getMailTextContent((Part)part.getContent(),content); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); getMailTextContent(bodyPart,content); } } }
Example #14
Source File: StripAttachmentTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void saveAttachmentShouldAddBinExtensionWhenNoFileNameExtension(TemporaryFolder temporaryFolder) throws Exception { //Given StripAttachment mailet = new StripAttachment(); FakeMailetConfig mci = FakeMailetConfig.builder() .setProperty("directory", temporaryFolder.getFolderPath()) .setProperty("pattern", ".*") .build(); mailet.init(mci); Part part = MimeMessageBuilder.bodyPartBuilder().build(); String fileName = "exampleWithoutSuffix"; //When Optional<String> maybeFilename = mailet.saveAttachmentToFile(part, Optional.of(fileName)); //Then assertThat(maybeFilename).isPresent(); String filename = maybeFilename.get(); assertThat(filename).startsWith("exampleWithoutSuffix"); assertThat(filename).endsWith(".bin"); }
Example #15
Source File: Mail.java From camunda-bpm-mail with Apache License 2.0 | 6 votes |
protected static void processMessagePartContent(Part part, Mail mail) throws MessagingException, IOException { if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { Attachment attachment = Attachment.from(part); mail.attachments.add(attachment); } else { if (part.isMimeType("text/plain")) { mail.text = (String) part.getContent(); } else if (part.isMimeType("text/html")) { mail.html = (String) part.getContent(); } } }
Example #16
Source File: NoteDetailActivity.java From ImapNote2 with GNU General Public License v3.0 | 6 votes |
private void GetPart(Part message) throws Exception { if (message.isMimeType("text/plain")) { Log.d(TAG,"+++ isMimeType text/plain (contentType):"+message.getContentType()); } else if (message.isMimeType("multipart/*")) { Log.d(TAG,"+++ isMimeType multipart/* (contentType):"+message.getContentType()); Object content = message.getContent(); Multipart mp = (Multipart) content; int count = mp.getCount(); for (int i = 0; i < count; i++) GetPart(mp.getBodyPart(i)); } else if (message.isMimeType("message/rfc822")) { Log.d(TAG,"+++ isMimeType message/rfc822/* (contentType):"+message.getContentType()); GetPart((Part) message.getContent()); } else if (message.isMimeType("image/jpeg")) { Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType()); } else if (message.getContentType().contains("image/")) { Log.d(TAG,"+++ isMimeType image/jpeg (contentType):"+message.getContentType()); } else { Object o = message.getContent(); if (o instanceof String) { Log.d(TAG,"+++ instanceof String"); } else if (o instanceof InputStream) { Log.d(TAG,"+++ instanceof InputStream"); } else Log.d(TAG,"+++ instanceof ???"); } }
Example #17
Source File: SpitterMailServiceImplTest.java From Project with Apache License 2.0 | 6 votes |
public void receiveTest() throws Exception { MimeMessage[] receivedMessages = mailServer.getReceivedMessages(); assertEquals(1, receivedMessages.length); assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject()); Address[] from = receivedMessages[0].getFrom(); assertEquals(1, from.length); assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress()); assertEquals(toEmail, ((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress()); MimeMultipart multipart = (MimeMultipart) receivedMessages[0].getContent(); Part part = null; for(int i=0;i<multipart.getCount();i++) { part = multipart.getBodyPart(i); System.out.println(part.getFileName()); System.out.println(part.getSize()); } }
Example #18
Source File: MimePackage.java From ats-framework with Apache License 2.0 | 5 votes |
private boolean isPartAttachment( MimePart part ) throws PackageException { try { String disposition = part.getDisposition(); if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) { return true; } } catch (MessagingException me) { throw new PackageException("Could not determine if part is an attachment", me); } return false; }
Example #19
Source File: StripAttachmentTest.java From james-project with Apache License 2.0 | 5 votes |
@Test void processMultipartPartMessageShouldReturnFalseWhenPartIsNotMultipart() throws Exception { //Given StripAttachment mailet = new StripAttachment(); Part part = new MimeBodyPart(new ByteArrayInputStream(new byte[0])); Mail mail = mock(Mail.class); //When boolean actual = mailet.processMultipartPartMessage(part, mail); //Then assertThat(actual).isFalse(); }
Example #20
Source File: EmailAttachment.java From cuba with Apache License 2.0 | 5 votes |
public static EmailAttachment createTextAttachment(String text, String encoding, String name) { byte[] data; try { data = text.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return new EmailAttachment(data, name, null, Part.ATTACHMENT, encoding); }
Example #21
Source File: Pop3Util.java From anyline with Apache License 2.0 | 5 votes |
/** * 判断邮件中是否包含附件 * * @param part part * @return 邮件中存在附件返回true,不存在返回false * @throws MessagingException MessagingException * @throws IOException IOException * @return boolean */ public static boolean isContainAttachment(Part part) throws MessagingException, IOException { boolean flag = false; if (part.isMimeType("multipart/*")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp .equalsIgnoreCase(Part.INLINE))) { flag = true; } else if (bodyPart.isMimeType("multipart/*")) { flag = isContainAttachment(bodyPart); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("application") != -1) { flag = true; } if (contentType.indexOf("name") != -1) { flag = true; } } if (flag) break; } } else if (part.isMimeType("message/rfc822")) { flag = isContainAttachment((Part) part.getContent()); } return flag; }
Example #22
Source File: EmailerTest.java From cuba with Apache License 2.0 | 5 votes |
private void doTestTextAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer(); String attachmentText = "Test Attachment Text"; EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt"); EmailInfo myInfo = EmailInfoBuilder.create() .setAddresses("[email protected]") .setCaption("Test") .setBody("Test") .setAttachments(textAttach) .build(); 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")); }
Example #23
Source File: EmailerTest.java From cuba with Apache License 2.0 | 5 votes |
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer(); byte[] imageBytes = new byte[]{1, 2, 3, 4, 5}; String fileName = "logo.png"; EmailAttachment imageAttach = new EmailAttachment(imageBytes, fileName, "logo"); EmailInfo myInfo = EmailInfoBuilder.create() .setAddresses("[email protected]") .setCaption("Test") .setBody("Test") .setAttachments(imageAttach) .build(); 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")); }
Example #24
Source File: EmailerTest.java From cuba with Apache License 2.0 | 5 votes |
private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer(); byte[] pdfBytes = new byte[]{1, 2, 3, 4, 6}; String fileName = "invoice.pdf"; EmailAttachment pdfAttach = new EmailAttachment(pdfBytes, fileName); EmailInfo myInfo = EmailInfoBuilder.create() .setAddresses("[email protected]") .setCaption("Test") .setBody("Test") .setAttachments(pdfAttach) .build(); 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")); }
Example #25
Source File: EmailReader.java From baleen with Apache License 2.0 | 5 votes |
private void writeFileToDisk(File destFile, Part part) throws IOException, MessagingException { try (FileOutputStream output = new FileOutputStream(destFile); InputStream input = part.getInputStream()) { byte[] buffer = new byte[4096]; int byteRead; while ((byteRead = input.read(buffer)) != -1) { output.write(buffer, 0, byteRead); } } catch (IOException ex) { throw new IOException("Unable to save attachment", ex); } }
Example #26
Source File: MimeMessageParser.java From eml-to-pdf-converter with Apache License 2.0 | 5 votes |
/*** * Walk the Mime Structure recursivly and execute the callback on every part. * @param p mime object * @param initial level of current depth of the part * @param callback Object holding the callback function * @throws Exception */ private static void walkMimeStructure(Part p, int level, WalkMimeCallback callback) throws Exception { callback.walkMimeCallback(p, level); if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) { walkMimeStructure(mp.getBodyPart(i), level + 1, callback); } } }
Example #27
Source File: DefaultAttachmentPredicate.java From ogham with Apache License 2.0 | 5 votes |
private boolean isDownloadableAttachment(Part p) { try { return Part.ATTACHMENT.equalsIgnoreCase(p.getDisposition()) || p.getFileName() != null; } catch(MessagingException e) { throw new FilterException("Failed to check if attachment is downloadable", e); } }
Example #28
Source File: EmailUtils.java From ogham with Apache License 2.0 | 5 votes |
private static boolean hasParent(Part part) { if (part instanceof Message) { return false; } if (part instanceof BodyPart) { return ((BodyPart) part).getParent() != null; } return false; }
Example #29
Source File: FluentPartAssert.java From ogham with Apache License 2.0 | 5 votes |
@SuppressWarnings("squid:S1168") private static List<String> getHeaderValues(Part part, String headerName) throws MessagingException { if (part != null) { String[] vals = part.getHeader(headerName); if (vals != null) { return asList(vals); } } return null; }
Example #30
Source File: StripAttachmentTest.java From james-project with Apache License 2.0 | 5 votes |
@Test void saveAttachmentShouldReturnAbsentWhenNoFilenameAtAll(TemporaryFolder temporaryFolder) throws Exception { StripAttachment mailet = new StripAttachment(); FakeMailetConfig mci = FakeMailetConfig.builder() .setProperty("directory", temporaryFolder.getFolderPath()) .setProperty("pattern", ".*\\.tmp") .build(); mailet.init(mci); Part part = MimeMessageBuilder.bodyPartBuilder().build(); Optional<String> maybeFilename = mailet.saveAttachmentToFile(part, ABSENT_MIME_TYPE); assertThat(maybeFilename).isEmpty(); }