List of usage examples for javax.mail Part INLINE
String INLINE
To view the source code for javax.mail Part INLINE.
Click Source Link
From source file:com.openkm.util.MailUtils.java
/** * Create a mail.//from ww w. j a va 2 s . co m * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.haulmont.cuba.core.app.EmailerTest.java
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException { emailerConfig.setFileStorageUsed(useFs); testMailSender.clearBuffer();/*ww w. ja va 2s . 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:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);/*from ww w . jav a2 s. co m*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Plain text Email test with attachment", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals("text/plain", message.getContentType()); org.jvnet.mock_javamail.Mailbox.clearAll(); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); verify(mockListener1, times(2)).getComponentId(); }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { 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); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { InputStream is = bodyPart.getInputStream(); saveFile(is, destDir, decodeText(bodyPart.getFileName())); } else if (bodyPart.isMimeType("multipart/*")) { saveAttachment(bodyPart, destDir); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); }/*from w ww. j a v a 2s .co m*/ } } } else if (part.isMimeType("message/rfc822")) { saveAttachment((Part) part.getContent(), destDir); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object/* ww w . j av a2s . c o m*/ */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java
private void retrieveBody(cfSession _Session, Part Mess, cfQueryResultData popData, int Row, File attachmentDir) throws Exception { if (Mess.isMimeType("multipart/*")) { Multipart mp = (Multipart) Mess.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) retrieveBody(_Session, mp.getBodyPart(i), popData, Row, attachmentDir); } else {//from w w w . j a v a 2 s. c om String filename = cfMailMessageData.getFilename(Mess); String dispos = Mess.getDisposition(); // note: text/enriched shouldn't be treated as a text part of the email (see bug #2227) if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && Mess.isMimeType("text/*") && !Mess.isMimeType("text/enriched")) { String content; String contentType = Mess.getContentType().toLowerCase(); // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7 if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) { content = new String(UTF7Converter.convert(readInputStream(Mess))); } else { try { content = (String) Mess.getContent(); } catch (UnsupportedEncodingException e) { content = "Unable to retrieve message body due to UnsupportedEncodingException:" + e.getMessage(); } catch (ClassCastException e) { // shouldn't happen but handle it gracefully content = new String(readInputStream(Mess)); } } if (Mess.isMimeType("text/html")) { popData.setCell(Row, 14, new cfStringData(content)); } else if (Mess.isMimeType("text/plain")) { popData.setCell(Row, 15, new cfStringData(content)); } popData.setCell(Row, 11, new cfStringData(content)); } else if (attachmentDir != null) { File outFile; if (filename == null) filename = "unknownfile"; outFile = getAttachedFilename(attachmentDir, filename, getDynamic(_Session, "GENERATEUNIQUEFILENAMES").getBoolean()); try { BufferedInputStream in = new BufferedInputStream(Mess.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( cfEngine.thisPlatform.getFileIO().getFileOutputStream(outFile)); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); //--[ Update the fields cfStringData cell = (cfStringData) popData.getCell(Row, 12); if (cell.getString().length() == 0) cell = new cfStringData(filename); else cell = new cfStringData(cell.getString() + "," + filename); popData.setCell(Row, 12, cell); cell = (cfStringData) popData.getCell(Row, 13); if (cell.getString().length() == 0) cell = new cfStringData(outFile.toString()); else cell = new cfStringData(cell.getString() + "," + outFile.toString()); popData.setCell(Row, 13, cell); } catch (Exception ignoreException) { } } } }
From source file:com.aurel.track.util.emailHandling.MailReader.java
/** * Processes part of a message/*w w w . j a v a2s. c o m*/ */ private static String handleSimplePart(Part part, List<EmailAttachment> attachments, boolean ignoreAttachments) throws MessagingException, IOException { // Check for content disposition and content type String disposition = part.getDisposition(); String contentType = part.getContentType(); LOGGER.debug("disposition=" + disposition); LOGGER.debug("Body type is: " + contentType); // tread if the part is a message boolean inlineMessage = part.isMimeType("message/rfc822"); if (inlineMessage) { LOGGER.debug("Inner message:" + part.getFileName()); Message subMessage = (Message) part.getContent(); StringBuffer s = handlePart(subMessage, attachments, ignoreAttachments); System.out.println(); return s.toString(); } if (disposition == null) { if ("image/BMP".equals(contentType)) { // BMP image add as attachment if (ignoreAttachments == false) { try { attachments.add(createEmailAttachment(part, "image.bmp")); } catch (Exception e) { // just ignore } } return null; } else if (part.isMimeType("text/*")) { return getText(part); } else { if (ignoreAttachments == false) { handleAttachment(part, attachments); } return null; } } if (disposition.equalsIgnoreCase(Part.INLINE)) { return handleInline(part, attachments, ignoreAttachments); } if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) { if (ignoreAttachments == false) { handleAttachment(part, attachments); } return null; } LOGGER.debug("Unknown disposition:" + disposition + "Threat as attachment"); if (ignoreAttachments == false) { handleAttachment(part, attachments); } return null; }
From source file:org.apache.camel.component.mail.MailBinding.java
private MimeMultipart createMixedMultipartAttachments(MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { // fill the body with text MimeMultipart multipart = new MimeMultipart(); multipart.setSubType("mixed"); addBodyToMultipart(configuration, multipart, exchange); String partDisposition = configuration.isUseInlineAttachments() ? Part.INLINE : Part.ATTACHMENT; if (exchange.getIn().hasAttachments()) { addAttachmentsToMultipart(multipart, partDisposition, exchange); }//from w w w . j a va2 s. co m return multipart; }
From source file:immf.SendMailBridge.java
private void parseBodypartmixed(SenderMail sendMail, BodyPart bp, String subtype, String parentSubtype) throws IOException { boolean limiterr = false; String badfile = null;//from w ww.ja va2 s . c o m try { String contentType = bp.getContentType().toLowerCase(); log.info("Bodypart ContentType:" + contentType); log.info("subtype:" + subtype); if (contentType.startsWith("multipart/")) { parseMultipart(sendMail, (Multipart) bp.getContent(), getSubtype(contentType), subtype); } else if (sendMail.getPlainTextContent() == null && contentType.startsWith("text/plain")) { // ???plain/text? String content = (String) bp.getContent(); log.info("set Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); sendMail.setPlainTextContent(content); // HTML??????<br>????????HtmlConverter? // ??????HTML???HTML??????? if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body>" + Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else { sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } } else if (sendMail.getHtmlContent() == null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ???text/html String content = (String) bp.getContent(); log.info("set Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); // 2?3?HTML?????????</body>??????? content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.setHtmlContent(content); } else { log.debug("attach"); // ???? String contentDisposition = bp.getDisposition(); if (contentDisposition != null && contentDisposition.equalsIgnoreCase(Part.INLINE)) { // SenderAttachment file = new SenderAttachment(); String uniqId = uniqId(); String fname = uniqId; String fname2 = Util.getFileName(bp); // iPhone?gifpng?????????????gif??(?png???gif?) if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); fname = fname + ".gif"; fname2 = getBasename(fname2) + ".gif"; file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setContentType(contentType); fname = fname + "." + getSubtype(contentType); file.setData(inputstream2bytes(bp.getInputStream())); } file.setInline(true); boolean inline = !this.forcePlainText & sendMail.checkAttachmentCapability(file); if (!inline) { file.setInline(false); if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = fname2; throw new Exception("Attachments: size limit or file count limit exceeds!"); } } if (inline) { file.setFilename(fname); if (bp.getHeader("Content-Id") == null) { file.setContentId(uniqId); } else { file.setContentId(bp.getHeader("Content-Id")[0]); } log.info("Inline Attachment(mixed) " + file.loggingString() + ", Hash:" + file.getHash()); // ??HTML? if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent( "<body><img src=\"cid:" + file.getContentId() + "\"><br>"); } else { sendMail.addHtmlWorkingContent("<img src=\"cid:" + file.getContentId() + "\"><br>"); } } else { file.setFilename(fname2); log.info("Attachment " + file.loggingString()); } sendMail.addAttachmentFileIdList(file); } else { // ? SenderAttachment file = new SenderAttachment(); file.setInline(false); file.setContentType(contentType); String fname = Util.getFileName(bp); if (fname == null && sendMail.getPlainTextContent() != null && contentType.startsWith("text/plain")) { // ??????? String content = (String) bp.getContent(); log.info("add Content text [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); log.debug(" conv " + content); // ??HTML????<br> sendMail.addPlainTextContent("\n" + content); sendMail.addHtmlWorkingContent( Util.easyEscapeHtml(content).replaceAll("\\r\\n", "<br>") + "<br>"); } else if (fname == null && sendMail.getHtmlContent() != null && contentType.startsWith("text/html") && (parentSubtype.equalsIgnoreCase("alternative") || parentSubtype.equalsIgnoreCase("related"))) { // ????text/html???? String content = (String) bp.getContent(); log.info("add Content html [" + content + "]"); String charset = (new ContentType(contentType)).getParameter("charset"); content = this.charConv.convert(content, charset); content = HtmlConvert.replaceAllCaseInsenstive(content, ".*<body[^>]*>", ""); content = HtmlConvert.replaceAllCaseInsenstive(content, "</body>.*", ""); log.debug(" conv " + content); sendMail.addHtmlContent(content); } else { // ?????? if (getSubtype(contentType).equalsIgnoreCase("png")) { file.setContentType("image/gif"); file.setFilename(getBasename(fname) + ".gif"); file.setData(inputstream2bytes(Util.png2gif(bp.getInputStream()))); } else { file.setFilename(fname); file.setData(inputstream2bytes(bp.getInputStream())); } if (!sendMail.checkAttachmentCapability(file)) { limiterr = true; badfile = file.getFilename(); throw new Exception("Attachments: size limit or file count limit exceeds!"); } sendMail.addAttachmentFileIdList(file); log.info("Attachment " + file.loggingString()); } } } } catch (Exception e) { log.error("parse bodypart error(mixed).", e); if (limiterr) { sendMail.addPlainTextContent("\n[(" + badfile + ")]"); if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("[(" + badfile + ")]<br>"); } if (sendMail.getHtmlWorkingContent() == null) { sendMail.setHtmlWorkingContent("<body>[(" + badfile + ")]<br>"); } else { sendMail.addHtmlWorkingContent("[(" + badfile + ")]<br>"); } } else { throw new IOException("BodyPart error(mixed)." + e.getMessage(), e); } } }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
public static void handlePart(String foldername, Part part) throws MessagingException, IOException { String disposition = part.getDisposition(); // String contentType = part.getContentType(); if ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) { saveFile(foldername, MimeUtility.decodeText(part.getFileName()), part.getInputStream()); }//w w w.ja v a2s . co m }