List of usage examples for javax.mail Multipart getContentType
public synchronized String getContentType()
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void main(String[] args) throws NoSuchProviderException, MessagingException { System.out.println("Salut"); // trustSSL(); /* final Properties props = new Properties(); props.put("mail.smtp.host", "my-mail-server"); props.put("mail.from", "me@example.com"); javax.mail.Session session = javax.mail.Session.getInstance(props, null); try {/*from w w w . j a va2s . com*/ MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, "you@example.com"); msg.setSubject("JavaMail hello world example"); msg.setSentDate(new Date()); msg.setText("Hello, world!\n"); Transport.send(msg); } catch (MessagingException mex) { System.out.println("send failed, exception: " + mex); }*/ final Properties props = new Properties(); //props.put("mail.host", "10.69.60.6"); //props.put("mail.user", "fenyo"); //props.put("mail.from", "fenyo@fenyo.net"); //props.put("mail.transport.protocol", "smtps"); //props.put("mail.store.protocol", "pop3s"); // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]] // final Provider[] providers = session.getProviders(); javax.mail.Session session = javax.mail.Session.getInstance(props, null); session.setDebug(true); //session.setDebug(false); // final Store store = session.getStore("pop3s"); // store.connect("10.69.60.6", 995, "fenyo", "PASSWORD"); // final Store store = session.getStore("imaps"); // store.connect("10.69.60.6", 993, "fenyo", "PASSWORD"); // System.out.println(store.getDefaultFolder().getMessageCount()); //final Store store = session.getStore("pop3"); final Store store = session.getStore("pop3s"); //final Store store = session.getStore("imaps"); // store.addStoreListener(new StoreListener() { // public void notification(StoreEvent e) { // String s; // if (e.getMessageType() == StoreEvent.ALERT) // s = "ALERT: "; // else // s = "NOTICE: "; // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage()); // } // }); //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD"); store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD"); //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD"); //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD"); //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD"); // final Folder[] folders = store.getPersonalNamespaces(); // for (Folder f : folders) { // System.out.println("Folder: " + f.getMessageCount()); // final Folder g = f.getFolder("INBOX"); // g.open(Folder.READ_ONLY); // System.out.println(" g:" + g.getMessageCount()); // } final Folder inbox = store.getDefaultFolder().getFolder("INBOX"); inbox.open(Folder.READ_ONLY); System.out.println("nmessages: " + inbox.getMessageCount()); final Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("message:"); System.out.println(" size: " + message.getSize()); try { if (message.getFrom() != null) System.out.println(" From: " + message.getFrom()[0]); } catch (final Exception ex) { System.out.println(ex.toString()); } System.out.println(" content-type: " + message.getContentType()); System.out.println(" disposition: " + message.getDisposition()); System.out.println(" description: " + message.getDescription()); System.out.println(" filename: " + message.getFileName()); System.out.println(" line count: " + message.getLineCount()); System.out.println(" message number: " + message.getMessageNumber()); System.out.println(" subject: " + message.getSubject()); try { if (message.getAllRecipients() != null) for (Address address : message.getAllRecipients()) System.out.println(" address: " + address); } catch (final Exception ex) { System.out.println(ex.toString()); } } for (Message message : messages) { System.out.println("-----------------------------------------------------"); Object content; try { content = message.getContent(); if (javax.mail.Multipart.class.isInstance(content)) { System.out.println("CONTENT OBJECT CLASS: MULTIPART"); final javax.mail.Multipart multipart = (javax.mail.Multipart) content; System.out.println("multipart content type: " + multipart.getContentType()); System.out.println("multipart count: " + multipart.getCount()); for (int i = 0; i < multipart.getCount(); i++) { System.out.println(" multipart body[" + i + "]: " + multipart.getBodyPart(i)); BodyPart part = multipart.getBodyPart(i); System.out.println(" content-type: " + part.getContentType()); } } else if (String.class.isInstance(content)) { System.out.println("CONTENT IS A STRING: {" + content + "}"); } else { System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString()); } } catch (IOException e) { e.printStackTrace(); } } store.close(); }
From source file:com.zotoh.crypto.MICUte.java
private static Object fromMP(Multipart mp) throws Exception { ContentType ct = new ContentType(mp.getContentType()); BodyPart bp;//from w ww . jav a 2s . co m Object contents; Object rc = null; int count = mp.getCount(); if ("multipart/mixed".equalsIgnoreCase(ct.getBaseType())) { if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); // check for EDI payload sent as attachment String ctype = bp.getContentType(); boolean getNextPart = false; if (ctype.indexOf("text/plain") >= 0) { if (contents instanceof String) { String bodyText = "This is a generated cryptographic message in MIME format"; if (((String) contents).startsWith(bodyText)) { getNextPart = true; } } if (!getNextPart) { // check for a content disposition // if disposition type is attachment, then this is a doc getNextPart = true; String disp = bp.getDisposition(); if (disp != null && disp.toLowerCase().equals("attachment")) getNextPart = false; } } if ((count >= 2) && getNextPart) { bp = mp.getBodyPart(1); contents = bp.getContent(); } if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } } else if (count > 0) { bp = mp.getBodyPart(0); contents = bp.getContent(); if (contents instanceof String) { rc = asBytes((String) contents); } else if (contents instanceof byte[]) { rc = contents; } else if (contents instanceof InputStream) { rc = contents; } else { String cn = contents == null ? "null" : contents.getClass().getName(); throw new Exception("Unsupport MIC object: " + cn); } } return rc; }
From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java
private void processPreviewMultiPart(Multipart multipart, Map<String, String> parts) throws MessagingException, IOException { logger.debug("Processing multipart of type {}", multipart.getContentType()); // FIXME : Implement strict Depth or breadth first ? for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); logger.debug("Processing part name {}, disposition = {}, type type = {}", new Object[] { part.getFileName(), part.getDisposition(), part.getContentType() }); if (part.getContent() instanceof Multipart) { processPreviewMultiPart((Multipart) part.getContent(), parts); } else if (part.getContentType().contains("text")) { String key = part.getContentType().split(";")[0]; String content = null; logger.debug("Add part with content type {} using key {}", part.getContentType(), key); if (key.endsWith("html")) { // <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> // Breaks preview ! content = part.getContent().toString().replaceAll("(?i)(?s)<meta.*charset=[^>]*>", ""); } else { content = part.getContent().toString(); }/* ww w . j a va 2 s .c om*/ appendPreviewContent(parts, key, content); } } }
From source file:com.zotoh.crypto.CryptoUte.java
/** * @param mp/*from w ww .jav a 2 s.co m*/ * @return * @throws IOException * @throws MessagingException * @throws GeneralSecurityException */ public static Object peekSmimeSignedContent(Multipart mp) throws IOException, MessagingException, GeneralSecurityException { tstArgIsType("mulitpart", mp, MimeMultipart.class); try { return new SMIMESignedParser((MimeMultipart) mp, getCharset(mp.getContentType(), "binary")).getContent() .getContent(); } catch (CMSException e) { throw new GeneralSecurityException(e); } }
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc/*from w w w. j av a 2 s . c o m*/ */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.zimbra.cs.mime.Mime.java
/** Determines the "primary/subtype" part of a Multipart's Content-Type * header. Uses a permissive, RFC2231-capable parser, and defaults * when appropriate. */// w w w . ja v a2 s . co m public static final String getContentType(Multipart multi) { return getContentType(multi.getContentType()); }
From source file:immf.SendMailBridge.java
private void parseMultipart(SenderMail sendMail, Multipart mp, String subtype, String parentSubtype) throws IOException { String contentType = mp.getContentType(); log.info("Multipart ContentType:" + contentType); try {/* ww w. j a va 2 s . co m*/ int count = mp.getCount(); log.info("count " + count); boolean hasInlinePart = false; if (subtype.equalsIgnoreCase("mixed")) { for (int i = 0; i < count; i++) { String d = mp.getBodyPart(i).getDisposition(); if (d != null && d.equalsIgnoreCase(Part.INLINE)) hasInlinePart = true; } } if (hasInlinePart) { log.info("parseBodypart(Content-Disposition:inline)"); for (int i = 0; i < count; i++) { parseBodypartmixed(sendMail, mp.getBodyPart(i), subtype, parentSubtype); } if (sendMail.getHtmlContent() != null) { sendMail.addHtmlContent("</body>"); } if (sendMail.getHtmlWorkingContent() != null) { sendMail.addHtmlWorkingContent("</body>"); } } else { for (int i = 0; i < count; i++) { parseBodypart(sendMail, mp.getBodyPart(i), subtype, parentSubtype); } } } catch (Exception e) { log.error("parse multipart error.", e); //throw new IOException("MimeMultiPart error."+e.getMessage(),e); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail.//from ww w . j a v a 2 s .c om * * @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) { 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.openkm.util.MailUtils.java
/** * Create a mail./* w w w.j a v a2s .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:org.apache.axis.attachments.MimeUtils.java
/** * Determine as efficiently as possible the content length for attachments in a mail Multipart. * @param mp is the multipart to be serarched. * @return the actual length.//from w w w . j av a 2s . c o m * * @throws javax.mail.MessagingException * @throws java.io.IOException */ public static long getContentLength(javax.mail.Multipart mp) throws javax.mail.MessagingException, java.io.IOException { int totalParts = mp.getCount(); long totalContentLength = 0; for (int i = 0; i < totalParts; ++i) { javax.mail.internet.MimeBodyPart bp = (javax.mail.internet.MimeBodyPart) mp.getBodyPart(i); totalContentLength += getContentLength(bp); } String ctype = mp.getContentType(); javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(ctype); String boundaryStr = ct.getParameter("boundary"); int boundaryStrLen = boundaryStr.length() + 4; // must add two for -- prefix and another two for crlf // there is one more boundary than parts // each parts data must have crlf after it. // last boundary has an additional --crlf return totalContentLength + boundaryStrLen * (totalParts + 1) + 2 * totalParts + +4; }