List of usage examples for javax.mail Part ATTACHMENT
String ATTACHMENT
To view the source code for javax.mail Part ATTACHMENT.
Click Source Link
From source file:Main.java
public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1);/*w ww . j a v a 2s . c om*/ } folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { System.out.println(messages[i].getSize() + " bytes long."); System.out.println(messages[i].getLineCount() + " lines."); String disposition = messages[i].getDisposition(); if (disposition == null) { ; // do nothing } else if (disposition.equals(Part.INLINE)) { System.out.println("This part should be displayed inline"); } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println("This part is an attachment"); String fileName = messages[i].getFileName(); System.out.println("The file name of this attachment is " + fileName); } String description = messages[i].getDescription(); if (description != null) { System.out.println("The description of this message is " + description); } } folder.close(false); }
From source file:net.prhin.mailman.MailMan.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty(resourceBundle.getString("mailman.mail.store"), resourceBundle.getString("mailman.protocol")); Session session = Session.getInstance(props); try {//from w w w . ja v a 2 s . com Store store = session.getStore(); store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"), resourceBundle.getString("mailman.password")); Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder")); inbox.open(Folder.READ_ONLY); inbox.getUnreadMessageCount(); Message[] messages = inbox.getMessages(); for (int i = 0; i <= messages.length / 2; i++) { Message tmpMessage = messages[i]; Multipart multipart = (Multipart) tmpMessage.getContent(); System.out.println("Multipart count: " + multipart.getCount()); for (int j = 0; j < multipart.getCount(); j++) { BodyPart bodyPart = multipart.getBodyPart(j); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) { MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent(); for (int k = 0; k < mimeMultipart.getCount(); k++) { if (mimeMultipart.getBodyPart(k).getFileName() != null) { printFileContents(mimeMultipart.getBodyPart(k)); } } } } else { printFileContents(bodyPart); } } } inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
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;/*from w w w. j a v a2s.c om*/ } 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; }
From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java
public void saveAllAttachment() { String protocol = ssl ? "imaps" : "imap"; Properties props = new Properties(); props.put("mail.store.protocol", protocol); try {// w w w .j av a2s. c o m Session session = Session.getInstance(props); Store store = session.getStore(); store.connect(host, port, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); for (Message msg : inbox.getMessages()) { if (!msg.isSet(Flags.Flag.SEEN)) { String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber(); Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && StringUtils.isNotEmpty(bodyPart.getFileName())) { MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName())); msg.setFlag(Flags.Flag.SEEN, true); } } } } } catch (IOException | MessagingException e) { log.error("? ? ?, : " + e.getMessage()); } }
From source file:org.springintegration.demo.service.EmailTransformer.java
public void handleMultipart(Multipart multipart, javax.mail.Message mailMessage, List<Message<?>> messages) { final int count; try {/*from w ww . jav a2s . com*/ count = multipart.getCount(); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e); } for (int i = 0; i < count; i++) { final BodyPart bp; try { bp = multipart.getBodyPart(i); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving body part.", e); } final String contentType; final String filename; final String disposition; final String subject; try { contentType = bp.getContentType(); filename = bp.getFileName(); disposition = bp.getDisposition(); subject = mailMessage.getSubject(); } catch (MessagingException e) { throw new IllegalStateException("Unable to retrieve body part meta data.", e); } if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { LOGGER.info("Handdling attachment '{}', type: '{}'", filename, contentType); } final Object content; try { content = bp.getContent(); } catch (IOException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } if (content instanceof String) { final Message<String> message = MessageBuilder.withPayload((String) content) .setHeader(FileHeaders.FILENAME, subject + ".txt").build(); messages.add(message); } else if (content instanceof InputStream) { InputStream inputStream = (InputStream) content; ByteArrayOutputStream bis = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, bis); } catch (IOException e) { throw new IllegalStateException( "Error while copying input stream to the ByteArrayOutputStream.", e); } Message<byte[]> message = MessageBuilder.withPayload((bis.toByteArray())) .setHeader(FileHeaders.FILENAME, filename).build(); messages.add(message); } else if (content instanceof javax.mail.Message) { handleMessage((javax.mail.Message) content, messages); } else if (content instanceof Multipart) { Multipart mp2 = (Multipart) content; handleMultipart(mp2, mailMessage, messages); } else { throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName()); } } }
From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java
private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException { try {/*from ww w . ja v a2s . c o m*/ if (partIndex >= parts.getCount()) { throw new StepFailedException("PartIndex too large.", this); } final BodyPart part = parts.getBodyPart(partIndex); final String contentType = part.getContentType(); if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) { throw new MessagingException("Actual contentType of '" + contentType + "' did not match expected contentType of '" + fContentType + "'"); } final String disp = part.getDisposition(); final String filename = part.getFileName(); final InputStream inputStream = part.getInputStream(); if (Part.ATTACHMENT.equals(disp)) { fFilename = filename; } else { fFilename = getClass().getName(); } ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType, "http://" + fFilename); } catch (IOException e) { throw new MessagingException("Error extracting part: " + e.getMessage()); } }
From source file:ch.algotrader.util.mail.EmailTransformer.java
/** * Parses any {@link Multipart} instances that contains attachments * * Will create the respective {@link EmailFragment}s representing those attachments. * @throws MessagingException/*w w w . j a va 2s . co m*/ */ public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException { final int count = multipart.getCount(); for (int i = 0; i < count; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String filename = bodyPart.getFileName(); String disposition = bodyPart.getDisposition(); if (filename == null && bodyPart instanceof MimeBodyPart) { filename = ((MimeBodyPart) bodyPart).getContentID(); } if (disposition == null) { //ignore message body } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) { try { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) { IOUtils.copy(bis, bos); emailFragments.add(new EmailFragment(filename, bos.toByteArray())); if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format("processing file: %s", new Object[] { filename })); } } } catch (IOException e) { throw new MessagingException("error processing streams", e); } } else { throw new MessagingException("unkown disposition " + disposition); } } }
From source file:org.openhie.openempi.service.MailEngineTest.java
public void testSendMessageWithAttachment() throws Exception { final String ATTACHMENT_NAME = "boring-attachment.txt"; //mock smtp server Wiser wiser = new Wiser(); int port = 2525 + (int) (Math.random() * 100); mailSender.setPort(port);/*from w w w . java 2 s .c o m*/ wiser.setPort(port); wiser.start(); Date dte = new Date(); String emailSubject = "grepster testSendMessageWithAttachment: " + dte; String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte; ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt"); mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); assertTrue(wiser.getMessages().size() == 1); WiserMessage wm = wiser.getMessages().get(0); MimeMessage mm = wm.getMimeMessage(); Object o = wm.getMimeMessage().getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart multi = (MimeMultipart) o; int numOfParts = multi.getCount(); boolean hasTheAttachment = false; for (int i = 0; i < numOfParts; i++) { BodyPart bp = multi.getBodyPart(i); String disp = bp.getDisposition(); if (disp == null) { //the body of the email Object innerContent = bp.getContent(); MimeMultipart innerMulti = (MimeMultipart) innerContent; assertEquals(emailBody, innerMulti.getBodyPart(0).getContent()); } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email hasTheAttachment = true; assertEquals(ATTACHMENT_NAME, bp.getFileName()); } else { fail("Did not expect to be able to get here."); } } assertTrue(hasTheAttachment); assertEquals(emailSubject, mm.getSubject()); }
From source file:com.crawlersick.nettool.GetattchmentFromMail1.java
public boolean fetchmailforattch() throws IOException, MessagingException { boolean fetchtest = false; Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); try {//from ww w. j a va 2 s.com Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect(IMapHost, MailId, MailPassword); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); totalmailcount = inbox.getMessageCount(); Message msg = null; for (int i = totalmailcount; i > 0; i--) { fromadd = ""; msg = inbox.getMessage(i); Address[] in = msg.getFrom(); for (Address address : in) { fromadd = address.toString() + fromadd; //System.out.println("FROM:" + address.toString()); } if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches( "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice")) break; } if (fromadd.equals("'")) { log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId); return fetchtest; } // Multipart mp = (Multipart) msg.getContent(); // BodyPart bp = mp.getBodyPart(0); sentdate = msg.getSentDate().toString(); subject = msg.getSubject(); Content = msg.getContent().toString(); log.log(Level.INFO, Content); log.log(Level.INFO, sentdate); localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data..."); LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent); Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) { continue; // dealing with attachments only } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream is = bodyPart.getInputStream(); //validvgbinary = IOUtils.toByteArray(is); int nRead; byte[] data = new byte[5000000]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); validvgbinary = buffer.toByteArray(); break; } fetchtest = true; } catch (Exception mex) { mex.printStackTrace(); } return fetchtest; }
From source file:immf.Util.java
public static void setFileName(Part part, String filename, String charset, String lang) throws MessagingException { ContentDisposition disposition;//from ww w . j a v a 2 s. c o m String[] strings = part.getHeader("Content-Disposition"); if (strings == null || strings.length < 1) { disposition = new ContentDisposition(Part.ATTACHMENT); } else { disposition = new ContentDisposition(strings[0]); disposition.getParameterList().remove("filename"); } part.setHeader("Content-Disposition", disposition.toString() + encodeParameter("filename", filename, charset, lang)); ContentType cType; strings = part.getHeader("Content-Type"); if (strings == null || strings.length < 1) { cType = new ContentType(part.getDataHandler().getContentType()); } else { cType = new ContentType(strings[0]); } try { // I want to public the MimeUtility#doEncode()!!! String mimeString = MimeUtility.encodeWord(filename, charset, "B"); // cut <CRLF>... StringBuffer sb = new StringBuffer(); int i; while ((i = mimeString.indexOf('\r')) != -1) { sb.append(mimeString.substring(0, i)); mimeString = mimeString.substring(i + 2); } sb.append(mimeString); cType.setParameter("name", new String(sb)); } catch (UnsupportedEncodingException e) { throw new MessagingException("Encoding error", e); } part.setHeader("Content-Type", cType.toString()); }