List of usage examples for javax.mail.internet MimeBodyPart getFileName
@Override public String getFileName() throws MessagingException
From source file:org.jevis.emaildatasource.EMailManager.java
/** * Find attachment and save it in inputstream * * @param message EMail message//from w w w . java 2s . co m * * @return List of InputStream */ private static List<InputStream> prepareAnswer(Message message, String filename) throws IOException, MessagingException { Multipart multiPart = (Multipart) message.getContent(); List<InputStream> input = new ArrayList<>(); // For all multipart contents for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i); String disp = part.getDisposition(); String partName = part.getFileName(); Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, "is Multipart"); // If multipart content is attachment if (!Part.ATTACHMENT.equalsIgnoreCase(disp) && !StringUtils.isNotBlank(partName)) { continue; // dealing with attachments only } if (Part.ATTACHMENT.equalsIgnoreCase(disp) || disp == null) { if (StringUtils.containsIgnoreCase(part.getFileName(), filename)) { Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Attach found: {0}", part.getFileName()); final long start = System.currentTimeMillis(); input.add(toInputStream(part));//add attach to answerlist final long answerDone = System.currentTimeMillis(); Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, ">>Attach to inputstream: " + (answerDone - start) + " Millisek."); } } } //for multipart check return input; }
From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java
@Test public void testWithAttachment() throws Exception { // Given://from w ww .j av a 2 s . c o m EmailService service = makeALocalMailer(); InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones"); String expectedSubject = "This is a Test Email"; String expectedTextBody = "This is a test with a PDF attachment."; List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>(); filesToAttach.add( new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile())); // When: service.sendWithAttachments(expectedTo, expectedSubject, expectedTextBody, filesToAttach); // Then: List<WiserMessage> messages = wiser.getMessages(); assertEquals("Number of messages sent;", 1, messages.size()); WiserMessage message = messages.get(0); MimeMessage mimeMessage = message.getMimeMessage(); assertEquals("Subject;", expectedSubject, mimeMessage.getSubject()); MimeMultipart body = ((MimeMultipart) mimeMessage.getContent()); assertEquals("Number of MIME Parts in the body;", 2, body.getCount()); MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1)); assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf")); assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName()); assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString())); }
From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java
public HashMap<String, String> fillAttachmentContentIds(ArrayList<MimeBodyPart> bodyparts) { HashMap<String, String> attmap = new HashMap<String, String>(); for (MimeBodyPart bodypart : bodyparts) { String fileName = null;//w w w . j a va 2 s . c om String cid = null; try { fileName = bodypart.getFileName(); cid = bodypart.getContentID(); } catch (MessagingException e) { logger.warn("Failed to retrieve attachment information", e); } if (!StringUtils.isBlank(cid) && fileName != null) { logger.debug("fillAttachmentContentIds: Treating attachment: {} with contentid {}", fileName, cid); String name = getAttachmentValidName(fileName); int nb = 1; if (!name.contains(".")) { name += ".ext"; } String newName = name; while (attmap.containsValue(newName)) { logger.debug("fillAttachmentContentIds: " + newName + " attachment already exists, renaming to " + name.replaceAll("(.*)\\.([^.]*)", "$1-" + nb + ".$2")); newName = name.replaceAll("(.*)\\.([^.]*)", "$1-" + nb + ".$2"); nb++; } attmap.put(cid, newName); } else { logger.debug("fillAttachmentContentIds: content ID is null, nothing to do"); } } return attmap; }
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 www.j a v a 2 s . c om*/ 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.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=image.png) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify that the Content-Disposition has the correct file namr assertTrue(part.getFileName().matches("image\\.png")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java
/** * Extracts mail content, and manage attachments. * //from ww w . ja v a 2s . c o m * @param part * @return * @throws MessagingException * @throws IOException * @throws UnsupportedEncodingException */ public MailContent extractMailContent(Part part) throws MessagingException, IOException { logger.debug("extractMailContent..."); if (part == null) { return null; } MailContent mailContent = new MailContent(); if (part.isMimeType("application/pkcs7-mime") || part.isMimeType("multipart/encrypted")) { logger.debug("Mail content is ENCRYPTED"); mailContent.setText( "<<<This e-mail part is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.>>>"); mailContent.setHtml( "<i><<<This e-mail is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.>>></i>"); mailContent.setEncrypted(true); return mailContent; } else { mailContent = extractPartsContent(part); } // TODO : filling attachment cids and creating xwiki attachments should be done in same method HashMap<String, String> attachmentsMap = fillAttachmentContentIds(mailContent.getAttachments()); String fileName = ""; for (MimeBodyPart currentbodypart : mailContent.getAttachments()) { try { String cid = currentbodypart.getContentID(); fileName = currentbodypart.getFileName(); // replace by correct name if filename was renamed (multiple attachments with same name) if (attachmentsMap.containsKey(cid)) { fileName = attachmentsMap.get(cid); } logger.debug("Treating attachment: " + fileName + " with contentid " + cid); if (fileName == null) { fileName = "file.ext"; } if (fileName.equals("oledata.mso") || fileName.endsWith(".wmz") || fileName.endsWith(".emz")) { logger.debug("Garbaging Microsoft crap !"); } else { String disposition = currentbodypart.getDisposition(); String attcontentType = currentbodypart.getContentType().toLowerCase(); logger.debug("Treating attachment of type: " + attcontentType); /* * XWikiAttachment wikiAttachment = new XWikiAttachment(); wikiAttachment.setFilename(fileName); * wikiAttachment.setContent(currentbodypart.getInputStream()); */ MailAttachment wikiAttachment = new MailAttachment(); wikiAttachment.setCid(cid); wikiAttachment.setFilename(fileName); byte[] filedatabytes = IOUtils.toByteArray(currentbodypart.getInputStream()); wikiAttachment.setData(filedatabytes); mailContent.addWikiAttachment(cid, wikiAttachment); } // end if } catch (Exception e) { logger.warn("Attachment " + fileName + " could not be treated", e); } } return mailContent; }
From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java
public Attach getAttach(Part part, String baseStorePath) throws MessagingException, IOException { MimeBodyPart mimePart = (MimeBodyPart) part; Attach attach = new Attach(); if (StringUtils.isEmpty(mimePart.getFileName())) { attach.setFileName("UNKNOWN"); } else {// w w w . jav a 2 s . c o m String fileName = mimePart.getFileName(); String encoded = System.getProperty("mail.mime.encodefilename"); if (Boolean.parseBoolean(encoded)) { fileName = MimeUtility.decodeText(fileName); } attach.setFileName(fileName); } ContentType type = new ContentType(mimePart.getContentType()); attach.setMimeType(type.getBaseType()); InputStream inputStream = mimePart.getDataHandler().getInputStream(); attach.buildMd5Checksum(inputStream); attach.buildPath(mimePart, baseStorePath); return attach; }
From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPart() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, Collections.<String, Object>emptyMap()); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=image.png) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify that the Content-Disposition has the correct file namr assertTrue(part.getFileName().matches("image\\.png")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPartWithHeader() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); Map<String, Object> parameters = Collections.singletonMap("headers", (Object) Collections.singletonMap("Content-Transfer-Encoding", "quoted-printable")); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, parameters); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=attachment8219195155963823979.tmp) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify the format of the generated temporary file containing our attachment data assertTrue(part.getFileName().matches("attachment.*\\.tmp")); assertArrayEquals(new String[] { "quoted-printable" }, part.getHeader("Content-Transfer-Encoding")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }
From source file:org.xwiki.mail.internal.AttachmentMimeBodyPartFactoryTest.java
@Test public void createAttachmentBodyPart() throws Exception { Environment environment = this.mocker.getInstance(Environment.class); when(environment.getTemporaryDirectory()).thenReturn(new File(TEMPORARY_DIRECTORY)); Attachment attachment = mock(Attachment.class); when(attachment.getContent()).thenReturn("Lorem Ipsum".getBytes()); when(attachment.getFilename()).thenReturn("image.png"); when(attachment.getMimeType()).thenReturn("image/png"); MimeBodyPart part = this.mocker.getComponentUnderTest().create(attachment, Collections.<String, Object>emptyMap()); assertEquals("<image.png>", part.getContentID()); // JavaMail adds some extra params to the content-type header // (e.g. image/png; name=attachment8219195155963823979.tmp) , we just verify the content type that we passed. assertTrue(part.getContentType().startsWith("image/png")); // We verify the format of the generated temporary file containing our attachment data assertTrue(part.getFileName().matches("attachment.*\\.tmp")); assertEquals("Lorem Ipsum", IOUtils.toString(part.getDataHandler().getInputStream())); }