List of usage examples for javax.mail.internet MimeBodyPart getContentID
@Override public String getContentID() throws MessagingException
From source file:com.szmslab.quickjavamail.receive.MessageLoader.java
/** * ?????MessageContent????/*from ww w . ja v a 2s . co m*/ * * @param multiPart * ? * @param msgContent * ???? * @throws MessagingException * @throws IOException */ private void setMultipartContent(Multipart multiPart, MessageContent msgContent) throws MessagingException, IOException { for (int i = 0; i < multiPart.getCount(); i++) { Part part = multiPart.getBodyPart(i); if (part.getContentType().indexOf("multipart") >= 0) { setMultipartContent((Multipart) part.getContent(), msgContent); } else { String disposition = part.getDisposition(); if (Part.ATTACHMENT.equals(disposition)) { // Disposition?"attachment"???ContentType???? msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } else { if (part.isMimeType("text/html")) { msgContent.html = part.getContent().toString(); } else if (part.isMimeType("text/plain")) { msgContent.text = part.getContent().toString(); } else { // Disposition?"inline"???ContentType?? if (Part.INLINE.equals(disposition)) { String cid = ""; if (part instanceof MimeBodyPart) { MimeBodyPart mimePart = (MimeBodyPart) part; cid = mimePart.getContentID(); } msgContent.inlineImageFileList .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } } } } } }
From source file:eagle.common.email.EagleMailClient.java
public boolean send(String from, String to, String cc, String title, String templatePath, VelocityContext context, Map<String, File> attachments) { if (attachments == null || attachments.isEmpty()) { return send(from, to, cc, title, templatePath, context); }/* w w w . j av a2s . co m*/ Template t = null; List<MimeBodyPart> mimeBodyParts = new ArrayList<MimeBodyPart>(); Map<String, String> cid = new HashMap<String, String>(); for (Map.Entry<String, File> entry : attachments.entrySet()) { final String attachment = entry.getKey(); final File attachmentFile = entry.getValue(); final MimeBodyPart mimeBodyPart = new MimeBodyPart(); if (attachmentFile != null && attachmentFile.exists()) { DataSource source = new FileDataSource(attachmentFile); try { mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(attachment); mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); mimeBodyPart.setContentID(attachment); cid.put(attachment, mimeBodyPart.getContentID()); mimeBodyParts.add(mimeBodyPart); } catch (MessagingException e) { LOG.error("Generate mail failed, got exception while attaching files: " + e.getMessage(), e); } } else { LOG.error("Attachment: " + attachment + " is null or not exists"); } } //TODO remove cid, because not used at all if (LOG.isDebugEnabled()) LOG.debug("Cid maps: " + cid); context.put("cid", cid); try { t = velocityEngine.getTemplate(BASE_PATH + templatePath); } catch (ResourceNotFoundException ex) { // LOGGER.error("Template not found:"+BASE_PATH + templatePath, ex); } if (t == null) { try { t = velocityEngine.getTemplate(templatePath); } catch (ResourceNotFoundException e) { try { t = velocityEngine.getTemplate("/" + templatePath); } catch (Exception ex) { LOG.error("Template not found:" + "/" + templatePath, ex); } } } final StringWriter writer = new StringWriter(); t.merge(context, writer); if (LOG.isDebugEnabled()) LOG.debug(writer.toString()); return this._send(from, to, cc, title, writer.toString(), mimeBodyParts); }
From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();/*from www .j ava2 s .co m*/ boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
From source file:org.apache.axiom.om.impl.MIMEOutputUtils.java
/** * @deprecated Use {@link OMMultipartWriter} instead. *//*from www .j av a 2s .c o m*/ public static void writeBodyPart(OutputStream outStream, MimeBodyPart part, String boundary) throws IOException, MessagingException { if (isDebugEnabled) { log.debug("Start writeMimeBodyPart for " + part.getContentID()); } outStream.write(CRLF); part.writeTo(outStream); outStream.write(CRLF); writeMimeBoundary(outStream, boundary); outStream.flush(); if (isDebugEnabled) { log.debug("End writeMimeBodyPart"); } }
From source file:org.apache.olingo.fit.Services.java
private InputStream exploreMultipart(final List<Attachment> attachments, final String boundary, final boolean continueOnError) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); Response res = null;/*w w w .java 2 s .c o m*/ boolean goon = true; for (int i = 0; i < attachments.size() && goon; i++) { try { final Attachment obj = attachments.get(i); bos.write(("--" + boundary).getBytes()); bos.write(Constants.CRLF); final Object content = obj.getDataHandler().getContent(); if (content instanceof MimeMultipart) { final ByteArrayOutputStream chbos = new ByteArrayOutputStream(); String lastContebtID = null; try { final Map<String, String> references = new HashMap<String, String>(); final String cboundary = "changeset_" + UUID.randomUUID().toString(); chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes()); chbos.write(Constants.CRLF); chbos.write(Constants.CRLF); for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) { final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j); lastContebtID = part.getContentID(); addChangesetItemIntro(chbos, lastContebtID, cboundary); res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references); if (!continueOnError && (res == null || res.getStatus() >= 400)) { throw new Exception("Failure processing changeset"); } addSingleBatchResponse(res, lastContebtID, chbos); references.put("$" + lastContebtID, res.getHeaderString("Location")); } chbos.write(("--" + cboundary + "--").getBytes()); chbos.write(Constants.CRLF); bos.write(chbos.toByteArray()); IOUtils.closeQuietly(chbos); } catch (Exception e) { LOG.warn("While processing changeset", e); IOUtils.closeQuietly(chbos); addItemIntro(bos, lastContebtID); if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, "1", bos); } else { addSingleBatchResponse(res, lastContebtID, bos); } goon = continueOnError; } } else { addItemIntro(bos, null); res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()), Collections.<String, String>emptyMap()); if (res.getStatus() >= 400) { goon = continueOnError; throw new Exception("Failure processing batch item"); } addSingleBatchResponse(res, bos); } } catch (Exception e) { if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, bos); } else { addSingleBatchResponse(res, bos); } } } bos.write(("--" + boundary + "--").getBytes()); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.V3Services.java
@Override public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary, final boolean contineOnError) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); Response res = null;//from w w w . j a v a 2s . co m boolean goon = true; for (int i = 0; i < attachments.size() && goon; i++) { try { final Attachment obj = attachments.get(i); bos.write(("--" + boundary).getBytes()); bos.write(Constants.CRLF); final Object content = obj.getDataHandler().getContent(); if (content instanceof MimeMultipart) { final Map<String, String> references = new HashMap<String, String>(); final String cboundary = "changeset_" + UUID.randomUUID().toString(); bos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes()); bos.write(Constants.CRLF); bos.write(Constants.CRLF); final ByteArrayOutputStream chbos = new ByteArrayOutputStream(); String lastContebtID = null; try { for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) { final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j); lastContebtID = part.getContentID(); addChangesetItemIntro(chbos, lastContebtID, cboundary); res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references); if (res == null || res.getStatus() >= 400) { throw new Exception("Failure processing changeset"); } addSingleBatchResponse(res, lastContebtID, chbos); references.put("$" + lastContebtID, res.getHeaderString("Location")); } bos.write(chbos.toByteArray()); IOUtils.closeQuietly(chbos); bos.write(("--" + cboundary + "--").getBytes()); bos.write(Constants.CRLF); } catch (Exception e) { LOG.warn("While processing changeset", e); IOUtils.closeQuietly(chbos); addChangesetItemIntro(bos, lastContebtID, cboundary); if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, "1", bos); } else { addSingleBatchResponse(res, lastContebtID, bos); } goon = contineOnError; } } else { addItemIntro(bos); res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream())); if (res.getStatus() >= 400) { goon = contineOnError; throw new Exception("Failure processing changeset"); } addSingleBatchResponse(res, bos); } } catch (Exception e) { if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, bos); } else { addSingleBatchResponse(res, bos); } } } bos.write(("--" + boundary + "--").getBytes()); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.V4Services.java
@Override public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary, final boolean continueOnError) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); Response res = null;// w w w .j av a 2 s . co m boolean goon = true; for (int i = 0; i < attachments.size() && goon; i++) { try { final Attachment obj = attachments.get(i); bos.write(("--" + boundary).getBytes()); bos.write(Constants.CRLF); final Object content = obj.getDataHandler().getContent(); if (content instanceof MimeMultipart) { final ByteArrayOutputStream chbos = new ByteArrayOutputStream(); String lastContebtID = null; try { final Map<String, String> references = new HashMap<String, String>(); final String cboundary = "changeset_" + UUID.randomUUID().toString(); chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes()); chbos.write(Constants.CRLF); chbos.write(Constants.CRLF); for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) { final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j); lastContebtID = part.getContentID(); addChangesetItemIntro(chbos, lastContebtID, cboundary); res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references); if (!continueOnError && (res == null || res.getStatus() >= 400)) { throw new Exception("Failure processing changeset"); } addSingleBatchResponse(res, lastContebtID, chbos); references.put("$" + lastContebtID, res.getHeaderString("Location")); } chbos.write(("--" + cboundary + "--").getBytes()); chbos.write(Constants.CRLF); bos.write(chbos.toByteArray()); IOUtils.closeQuietly(chbos); } catch (Exception e) { LOG.warn("While processing changeset", e); IOUtils.closeQuietly(chbos); addItemIntro(bos, lastContebtID); if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, "1", bos); } else { addSingleBatchResponse(res, lastContebtID, bos); } goon = continueOnError; } } else { addItemIntro(bos); res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream())); if (res.getStatus() >= 400) { goon = continueOnError; throw new Exception("Failure processing batch item"); } addSingleBatchResponse(res, bos); } } catch (Exception e) { if (res == null || res.getStatus() < 400) { addErrorBatchResponse(e, bos); } else { addSingleBatchResponse(res, bos); } } } bos.write(("--" + boundary + "--").getBytes()); return new ByteArrayInputStream(bos.toByteArray()); }
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 ww w. jav a2 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.contrib.mail.internal.JavamailMessageParser.java
/** * Extracts mail content, and manage attachments. * // w w w .ja va 2s . c om * @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.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;/*from w w w . java 2 s . c o m*/ 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; }