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:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java
private static String processMessagePart(final Part part) throws MessagingException { final String disp = part.getDisposition(); final String contentType = part.getContentType(); if (Part.ATTACHMENT.equals(disp)) { return " <part type=\"attachment\" filename=\"" + part.getFileName() + "\" contentType=\"" + extractBaseContentType(contentType) + "\"/>" + LS; }/*from w w w .j av a 2 s . c o m*/ return " <part type=\"inline\" contentType=\"" + extractBaseContentType(contentType) + "\"/>" + LS; }
From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java
@Test 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. j a va 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"); // a null from should work mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME); mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); // one without and one with from assertTrue(wiser.getMessages().size() == 2); 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.stimulus.archiva.extraction.MessageExtraction.java
private static void dumpPart(Part p, Hashtable<String, Part> attachments, Hashtable<String, String> inlines, Hashtable<String, String> images, Hashtable<String, String> nonImages, ArrayList<String> mimeTypes, String subject) throws Exception { mimeTypes.add(p.getContentType());//from ww w .j a va 2 s . c om if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); String fname = p.getFileName(); if (fname != null) { try { fname = MimeUtility.decodeText(fname); } catch (Exception e) { logger.debug("cannot decode filename:" + e.getMessage()); } } if ((disp != null && Compare.equalsIgnoreCase(disp, Part.ATTACHMENT)) || fname != null) { String filename = getFilename(subject, p); if (!filename.equalsIgnoreCase("winmail.dat")) { attachments.put(filename, p); } /*if (p.isMimeType("image/*")) { String str[] = p.getHeader("Content-ID"); if (str != null) images.put(filename,str[0]); else images.put(filename, filename); } return;*/ } } if (p.isMimeType("text/plain")) { String str = ""; if (inlines.containsKey("text/plain")) str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n"; inlines.put("text/plain", str + getTextContent(p)); } else if (p.isMimeType("text/html")) { inlines.put("text/html", getTextContent(p)); } else if (p.isMimeType("text/xml")) { attachments.put(getFilename(subject, p), p); } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); for (int i = 0; i < mp.getCount(); i++) dumpPart(mp.getBodyPart(i), attachments, inlines, images, nonImages, mimeTypes, subject); } else if (p.isMimeType("message/rfc822")) { dumpPart((Part) p.getContent(), attachments, inlines, images, nonImages, mimeTypes, subject); } else if (p.isMimeType("application/ms-tnef")) { Part tnefpart = TNEFMime.convert(null, p, false); if (tnefpart != null) { dumpPart((Part) tnefpart, attachments, inlines, images, nonImages, mimeTypes, subject); } } else if (p.isMimeType("application/*")) { String filename = getFilename("application", p); attachments.put(filename, p); String str[] = p.getHeader("Content-ID"); if (str != null) nonImages.put(filename, str[0]); } else if (p.isMimeType("image/*")) { String fileName = getFilename("image", p); attachments.put(fileName, p); String str[] = p.getHeader("Content-ID"); if (str != null) images.put(fileName, str[0]); else images.put(fileName, fileName); } else { String contentType = p.getContentType(); Object o = p.getContent(); if (o instanceof String) { String str = ""; if (inlines.containsKey("text/plain")) str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n"; inlines.put(contentType, str + (String) o); } else { String fileName = getFilenameFromContentType("attach", contentType); attachments.put(fileName, p); } } }
From source file:server.MailPop3Expert.java
@Override public void run() { //obtengo la agenda List<String> agenda = XmlParcerExpert.getInstance().getAgenda(); while (store.isConnected()) { try {// w ww.j a va 2 s . co m // Abre la carpeta INBOX Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // Obtiene los mails Message[] arrayMessages = folderInbox.getMessages(); //procesa los mails for (int i = 0; i < arrayMessages.length; i++) { Message message = arrayMessages[i]; Address[] fromAddress = message.getFrom(); String from = fromAddress[0].toString(); String subject = message.getSubject(); String sentDate = message.getSentDate().toString(); String messageContent = ""; String contentType = message.getContentType(); if (contentType.contains("multipart")) { // Si el contenido es mulpart Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { // si contiene un archivo } else { // el contenido del mensaje messageContent = part.getContent().toString(); } } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = message.getContent(); if (content != null) { messageContent = content.toString(); } } //parseo del from if (from.contains("<")) { from = from.substring(from.indexOf("<") + 1, from.length() - 1); } //si esta en la agenda if (agenda.contains(from)) { //obtiene la trama try { messageContent = messageContent.substring(messageContent.indexOf(">"), messageContent.indexOf("<") + 4); if (messageContent.startsWith(">") && messageContent.endsWith("<")) { //procesa el mail XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent); frame.loadMails(); } } catch (Exception e) { e.printStackTrace(); } } else { //no lo guarda } } folderInbox.close(false); //duerme el hilo por el tiempo de la frecuencia Thread.sleep(frecuency * 60 * 1000); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:de.elomagic.mag.AbstractTest.java
protected MimeMessage createMimeMessage(String filename) throws Exception { MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); textPart.setDisposition(Part.INLINE); MimeBodyPart binaryPart = new MimeBodyPart(); InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); binaryPart.setContent(getOriginalMailAttachment(), "application/pdf"); binaryPart.setDisposition(Part.ATTACHMENT); binaryPart.setFileName(filename);//from www . j a v a 2 s.c o m Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(binaryPart); MimeMessage message = new MimeMessage(greenMail.getImap().createSession()); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("mailuser@localhost.com") }); message.setSubject("Another test mail subject"); message.setContent(mp); // return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup()); }
From source file:de.saly.elasticsearch.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }/*from w w w.j a v a 2 s . c o m*/ im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public static List<Attachment> getMessageAttachments(MimeMessage message) { List<Attachment> attachments = new LinkedList<>(); try {/*from w ww. ja v a 2 s. co m*/ Multipart multipartMessage = (Multipart) message.getContent(); for (int i = 0; i < multipartMessage.getCount(); i++) { BodyPart bodyPart = multipartMessage.getBodyPart(i); if (bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { byte[] content = IOUtils.toByteArray(bodyPart.getInputStream()); attachments.add(new Attachment(bodyPart.getContentType(), bodyPart.getFileName(), Base64.encodeBase64String(content))); } } } catch (Exception e) { // do nothing } return attachments; }
From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java
public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException { log.trace("marshal(ShsMessage, OutputStream)"); MimeMultipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); try {//from www . j a v a 2s. co m ShsLabel label = shsMessage.getLabel(); if (label == null) { throw new IllegalMessageStructureException("label not found in shs message"); } Content content = label.getContent(); if (content == null) { throw new IllegalMessageStructureException("label/content not found in shs label"); } else { // we will update this according to our data parts below. content.getDataOrCompound().clear(); String contentId = content.getContentId(); content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID))); } List<DataPart> dataParts = shsMessage.getDataParts(); if (dataParts.isEmpty()) { throw new IllegalMessageStructureException("dataparts not found in message"); } for (DataPart dp : dataParts) { Data data = new Data(); data.setDatapartType(dp.getDataPartType()); data.setFilename(dp.getFileName()); if (dp.getContentLength() != null && dp.getContentLength() > 0) data.setNoOfBytes("" + dp.getContentLength()); content.getDataOrCompound().add(data); } bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1"); bodyPart.setHeader("Content-Transfer-Encoding", "binary"); multipart.addBodyPart(bodyPart); for (DataPart dataPart : dataParts) { bodyPart = new MimeBodyPart(); bodyPart.setDisposition(Part.ATTACHMENT); if (StringUtils.isNotBlank(dataPart.getFileName())) { bodyPart.setFileName(dataPart.getFileName()); } bodyPart.setDataHandler(dataPart.getDataHandler()); if (dataPart.getTransferEncoding() != null) { bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase()); } multipart.addBodyPart(bodyPart); } MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject("SHS Message"); mimeMessage.addHeader("Content-Transfer-Encoding", "binary"); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); String ignoreList[] = { "Message-ID" }; mimeMessage.writeTo(outputStream, ignoreList); outputStream.flush(); } catch (Exception e) { if (e instanceof IllegalMessageStructureException) { throw (IllegalMessageStructureException) e; } throw new IllegalMessageStructureException(e); } }
From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java
/** * Parses any {@link Multipart} instances that contain text or Html attachments, * {@link InputStream} instances, additional instances of {@link Multipart} * or other attached instances of {@link javax.mail.Message}. * * Will create the respective {@link EmailFragment}s representing those attachments. * * Instances of {@link javax.mail.Message} are delegated to * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances * of {@link Multipart} are delegated to * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}. * * @param directory Must not be null/*w ww .j ava 2 s . c o m*/ * @param multipart Must not be null * @param mailMessage Must not be null * @param emailFragments Must not be null */ public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage, List<EmailFragment> emailFragments) { Assert.notNull(directory, "The directory must not be null."); Assert.notNull(multipart, "The multipart object to be parsed must not be null."); Assert.notNull(mailMessage, "The mail message to be parsed must not be null."); Assert.notNull(emailFragments, "The collection of emailfragments must not be null."); final int count; try { count = multipart.getCount(); if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count)); } } 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; String filename; final String disposition; final String subject; try { contentType = bp.getContentType(); filename = bp.getFileName(); disposition = bp.getDisposition(); subject = mailMessage.getSubject(); if (filename == null && bp instanceof MimeBodyPart) { filename = ((MimeBodyPart) bp).getContentID(); } } catch (MessagingException e) { throw new IllegalStateException("Unable to retrieve body part meta data.", e); } if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format( "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'", new Object[] { contentType, filename, disposition, subject })); } if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", 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) { if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { emailFragments.add(new EmailFragment(directory, i + "-" + filename, content)); LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType)); } else { final String textFilename; final ContentType ct; try { ct = new ContentType(contentType); } catch (ParseException e) { throw new IllegalStateException("Error while parsing content type '" + contentType + "'.", e); } if ("text/plain".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.txt"; } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.html"; } else { textFilename = "message.other"; } emailFragments.add(new EmailFragment(directory, textFilename, content)); } } else if (content instanceof InputStream) { final InputStream inputStream = (InputStream) content; final ByteArrayOutputStream bis = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, bis); } catch (IOException e) { throw new IllegalStateException( "Error while copying input stream to the ByteArrayOutputStream.", e); } emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray())); } else if (content instanceof javax.mail.Message) { handleMessage(directory, (javax.mail.Message) content, emailFragments); } else if (content instanceof Multipart) { final Multipart mp2 = (Multipart) content; handleMultipart(directory, mp2, mailMessage, emailFragments); } else { throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName()); } } }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments, EmailRiverConfig config)//from www . ja va 2 s . c o m throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { if (attachments == null) { attachments = new ArrayList<AttachmentInfo>(); } boolean hasAttachment = false; try { hasAttachment = isContainAttachment(message); } catch (MessagingException e) { logger.error("save attachment", e); } catch (IOException e) { logger.error("save attachment", e); } if (hasAttachment) { if (message.isMimeType("multipart/*")) { Multipart multipart = (Multipart) message.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))) { InputStream is = bodyPart.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = -1; while ((len = bis.read()) != -1) { bos.write(len); } bos.close(); bis.close(); byte[] data = bos.toByteArray(); String fileId = uploadFileToWeedfs(data, config); if (fileId != null) { AttachmentInfo info = new AttachmentInfo(); info.fileId = fileId; info.fileName = decodeText(bodyPart.getFileName()); info.fileSize = data.length; attachments.add(info); } } else if (bodyPart.isMimeType("multipart/*")) { attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config)); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config)); } } } } else if (message.isMimeType("message/rfc822")) { attachments.addAll(saveAttachmentToWeedFs(message, attachments, config)); } } return attachments; }