當前位置: 首頁>>代碼示例>>Java>>正文


Java Part.getFileName方法代碼示例

本文整理匯總了Java中javax.mail.Part.getFileName方法的典型用法代碼示例。如果您正苦於以下問題:Java Part.getFileName方法的具體用法?Java Part.getFileName怎麽用?Java Part.getFileName使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.mail.Part的用法示例。


在下文中一共展示了Part.getFileName方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: downloadAttachment

import javax.mail.Part; //導入方法依賴的package包/類
private void downloadAttachment(Part part, String folderPath) throws MessagingException, IOException {
	String disPosition = part.getDisposition();
	String fileName = part.getFileName();
	String decodedAttachmentName = null;

	if (fileName != null) {
		LOGGER.info("Attached File Name :: " + fileName);
		decodedAttachmentName = MimeUtility.decodeText(fileName);
		LOGGER.info("Decoded string :: " + decodedAttachmentName);
		decodedAttachmentName = Normalizer.normalize(decodedAttachmentName, Normalizer.Form.NFC);
		LOGGER.info("Normalized string :: " + decodedAttachmentName);
		int extensionIndex = decodedAttachmentName.indexOf(EXTENSION_VALUE_46);
		extensionIndex = extensionIndex == -1 ? decodedAttachmentName.length() : extensionIndex;
		File parentFile = new File(folderPath);
		LOGGER.info("Updating file name if any file with the same name exists. File : " + decodedAttachmentName);
		decodedAttachmentName = FileUtils.getUpdatedFileNameForDuplicateFile(decodedAttachmentName.substring(0, extensionIndex), parentFile, -1)
				+ decodedAttachmentName.substring(extensionIndex);

		LOGGER.info("Updated file name : " + decodedAttachmentName);
	}
	if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
		File file = new File(folderPath + File.separator + decodedAttachmentName);
		file.getParentFile().mkdirs();
		saveEmailAttachment(file, part);
	}
}
 
開發者ID:kuzavas,項目名稱:ephesoft,代碼行數:27,代碼來源:MailReceiverServiceImpl.java

示例2: getContent

import javax.mail.Part; //導入方法依賴的package包/類
public static String getContent(Part message) throws MessagingException,
        IOException {

    if (message.getContent() instanceof String) {
        return message.getContentType() + ": " + message.getContent() + " \n\t";
    } else if (message.getContent() != null && message.getContent() instanceof Multipart) {
        Multipart part = (Multipart) message.getContent();
        String text = "";
        for (int i = 0; i < part.getCount(); i++) {
            BodyPart bodyPart = part.getBodyPart(i);
            if (!Message.ATTACHMENT.equals(bodyPart.getDisposition())) {
                text += getContent(bodyPart);
            } else {
                text += "attachment: \n" +
                        "\t\t name: " + (StringUtils.isEmpty(bodyPart.getFileName()) ? "none"
                        : bodyPart.getFileName()) + "\n" +
                        "\t\t disposition: " + bodyPart.getDisposition() + "\n" +
                        "\t\t description: " + (StringUtils.isEmpty(bodyPart.getDescription()) ? "none"
                        : bodyPart.getDescription()) + "\n\t";
            }
        }
        return text;
    }
    if (message.getContent() != null && message.getContent() instanceof Part) {
        if (!Message.ATTACHMENT.equals(message.getDisposition())) {
            return getContent((Part) message.getContent());
        } else {
            return "attachment: \n" +
                    "\t\t name: " + (StringUtils.isEmpty(message.getFileName()) ? "none"
                    : message.getFileName()) + "\n" +
                    "\t\t disposition: " + message.getDisposition() + "\n" +
                    "\t\t description: " + (StringUtils.isEmpty(message.getDescription()) ? "none"
                    : message.getDescription()) + "\n\t";
        }
    }

    return "";
}
 
開發者ID:GojaFramework,項目名稱:goja,代碼行數:39,代碼來源:EMail.java

示例3: getFilename

import javax.mail.Part; //導入方法依賴的package包/類
public static String getFilename( Part Mess ) throws MessagingException{
// Part.getFileName() doesn't take into account any encoding that may have been 
// applied to the filename so in order to obtain the correct filename we
// need to retrieve it from the Content-Disposition

String [] contentType = Mess.getHeader( "Content-Disposition" );
	if ( contentType != null && contentType.length > 0 ){
		int nameStartIndx = contentType[0].indexOf( "filename=\"" );
		if ( nameStartIndx != -1 ){
			String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) );
			try {
			filename = MimeUtility.decodeText( filename );
			return filename;
		} catch (UnsupportedEncodingException e) {}
		}  		
	}

	// couldn't determine it using the above, so fall back to more reliable but 
// less correct option
	return Mess.getFileName();
}
 
開發者ID:OpenBD,項目名稱:openbd-core,代碼行數:22,代碼來源:cfMailMessageData.java

示例4: doTag

import javax.mail.Part; //導入方法依賴的package包/類
@Override
public void doTag() throws IOException, JspException {
    PageContext pageContext = (PageContext)getJspContext();
    JspWriter out = pageContext.getOut();
    
    try {
        // make an HTML link for each attachment
        List<Part> parts = email.getParts();
        for (int partIndex=0; partIndex<parts.size(); partIndex++) {
            Part part = parts.get(partIndex);
            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                String filename = part.getFileName();
                out.println("<a href=\"showAttachment?messageID=" + email.getMessageID() + "&folder=" + folder + "&part=" + partIndex + "\">" +
                        filename + "</a> (" + Util.getHumanReadableSize(part) + ") <br/>");
            }
        }
    } catch (MessagingException e) {
        throw new JspException("Can't parse email.", e);
    }
}
 
開發者ID:NoYouShutup,項目名稱:CryptMeme,代碼行數:21,代碼來源:ShowAttachmentsTag.java

示例5: SubethaEmailMessagePart

import javax.mail.Part; //導入方法依賴的package包/類
/**
 * Object can be built on existing message part only.
 * 
 * @param messagePart Message part.
 */
public SubethaEmailMessagePart(Part messagePart)
{
    ParameterCheck.mandatory("messagePart", messagePart);

    try
    {
        fileSize = messagePart.getSize();
        fileName = messagePart.getFileName();
        contentType = messagePart.getContentType();

        Matcher matcher = encodingExtractor.matcher(contentType);
        if (matcher.find())
        {
            encoding = matcher.group(1);
            if (!Charset.isSupported(encoding))
            {
                throw new EmailMessageException(ERR_UNSUPPORTED_ENCODING, encoding);
            }
        }

        try
        {
            contentInputStream = messagePart.getInputStream(); 
        }
        catch (Exception ex)
        {
            throw new EmailMessageException(ERR_FAILED_TO_READ_CONTENT_STREAM, ex.getMessage());
        }
    }
    catch (MessagingException e)
    {
        throw new EmailMessageException(ERR_INCORRECT_MESSAGE_PART, e.getMessage());
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:40,代碼來源:SubethaEmailMessagePart.java

示例6: getPartFileName

import javax.mail.Part; //導入方法依賴的package包/類
/**
 * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter.
 * 
 * @param defaultPrefix This prefix fill be used for generating file name.
 * @param messagePart A part of message
 * @return File name.
 * @throws MessagingException
 */
private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException
{
    String fileName = messagePart.getFileName();
    if (fileName != null)
    {
        try
        {
            fileName = MimeUtility.decodeText(fileName);
        }
        catch (UnsupportedEncodingException ex)
        {
            // Nothing to do :)
        }
    }
    else
    {
        fileName = defaultPrefix;
        if (messagePart.isMimeType(MIME_PLAIN_TEXT))
            fileName += ".txt";
        else if (messagePart.isMimeType(MIME_HTML_TEXT))
            fileName += ".html";
        else if (messagePart.isMimeType(MIME_XML_TEXT))
            fileName += ".xml";
        else if (messagePart.isMimeType(MIME_IMAGE))
            fileName += ".gif";
    }
    return fileName;
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:37,代碼來源:SubethaEmailMessage.java

示例7: handleMimeMessages

import javax.mail.Part; //導入方法依賴的package包/類
protected String handleMimeMessages(Message message,Map<String,byte[]> attachmentMap)
        throws Exception{

    String emailBody = null;
    Multipart multipart = (Multipart) message.getContent();
    for (int j = 0, m = multipart.getCount(); j < m; j++) {
        Part part = multipart.getBodyPart(j);
        String disposition = part.getDisposition();
        boolean isAttachment = false;
        if (disposition != null && (disposition.equals(Part.ATTACHMENT)
                || (disposition.equals(Part.INLINE)))) {
            isAttachment = true;
            InputStream input = part.getInputStream();
            String fileName = part.getFileName();
            String contentType = part.getContentType();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            if (saveAttachment(input, output)) {
                byte[] encodedByte = new Base64().encode(output.toByteArray());
                if (encodedByte != null && fileName != null && contentType != null) {
                    attachmentMap.put(fileName+"~"+contentType, encodedByte);
                }
            }
        }
        if (!isAttachment && part.getContentType().startsWith("text/")){
            emailBody = (String) part.getContent();
        }
    }
    return emailBody;
}
 
開發者ID:CenturyLinkCloud,項目名稱:mdw,代碼行數:30,代碼來源:MDWEmailListener.java

示例8: getAttachments

import javax.mail.Part; //導入方法依賴的package包/類
/**
 * Extracts the attachments from the mail.
 *
 * @param message
 *            The message.
 * @return Collection of attachments as {@link AttachmentTO}.
 * @throws IOException
 *             Exception.
 * @throws MessagingException
 *             Exception.
 */
public static Collection<AttachmentTO> getAttachments(Message message)
        throws MessagingException, IOException {
    Collection<AttachmentTO> attachments = new ArrayList<AttachmentTO>();
    Collection<Part> parts = getAllParts(message);
    for (Part part : parts) {
        String disposition = part.getDisposition();
        String contentType = part.getContentType();
        if (StringUtils.containsIgnoreCase(disposition, "inline")
                || StringUtils.containsIgnoreCase(disposition, "attachment")
                || StringUtils.containsIgnoreCase(contentType, "name=")) {
            String fileName = part.getFileName();
            Matcher matcher = FILENAME_PATTERN.matcher(part.getContentType());
            if (matcher.matches()) {
                fileName = matcher.group(1);
                fileName = StringUtils.substringBeforeLast(fileName, ";");
            }
            if (StringUtils.isNotBlank(fileName)) {
                fileName = fileName.replace("\"", "").replace("\\\"", "");
                fileName = MimeUtility.decodeText(fileName);
                if (fileName.endsWith("?=")) {
                    fileName = fileName.substring(0, fileName.length() - 2);
                }
                fileName = fileName.replace("?", "_");
                AttachmentTO attachmentTO = new AttachmentStreamTO(part.getInputStream());
                attachmentTO.setContentLength(part.getSize());
                attachmentTO.setMetadata(new ContentMetadata());
                attachmentTO.getMetadata().setFilename(fileName);
                if (StringUtils.isNotBlank(contentType)) {
                    contentType = contentType.split(";")[0].toLowerCase();
                }
                attachmentTO.setStatus(AttachmentStatus.UPLOADED);
                attachments.add(attachmentTO);
            }
        }
    }
    return attachments;
}
 
開發者ID:Communote,項目名稱:communote-server,代碼行數:49,代碼來源:MailMessageHelper.java

示例9: extractAttachmentsFromMultipart

import javax.mail.Part; //導入方法依賴的package包/類
protected void extractAttachmentsFromMultipart(Multipart mp, Map<String, DataHandler> map)
    throws MessagingException, IOException {

    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);
        LOG.trace("Part #" + i + ": " + part);

        if (part.isMimeType("multipart/*")) {
            LOG.trace("Part #" + i + ": is mimetype: multipart/*");
            extractAttachmentsFromMultipart((Multipart) part.getContent(), map);
        } else {
            String disposition = part.getDisposition();
            String fileName = part.getFileName();

            if (LOG.isTraceEnabled()) {
                LOG.trace("Part #{}: Disposition: {}", i, disposition);
                LOG.trace("Part #{}: Description: {}", i, part.getDescription());
                LOG.trace("Part #{}: ContentType: {}", i, part.getContentType());
                LOG.trace("Part #{}: FileName: {}", i, fileName);
                LOG.trace("Part #{}: Size: {}", i, part.getSize());
                LOG.trace("Part #{}: LineCount: {}", i, part.getLineCount());
            }

            if (validDisposition(disposition, fileName)
                    || fileName != null) {
                LOG.debug("Mail contains file attachment: {}", fileName);
                if (!map.containsKey(fileName)) {
                    // Parts marked with a disposition of Part.ATTACHMENT are clearly attachments
                    map.put(fileName, part.getDataHandler());
                } else {
                    LOG.warn("Cannot extract duplicate file attachment: {}.", fileName);
                }
            }
        }
    }
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:37,代碼來源:MailBinding.java

示例10: getMailPartAsText

import javax.mail.Part; //導入方法依賴的package包/類
public static String getMailPartAsText(final Part part) throws MessagingException, IOException {
	String partString = "";
	if (part.isMimeType("text/*")) {
		partString = (String) part.getContent();
	} else if (part.isMimeType("image/*")) {
		final String contentType = part.getContentType();
		final String disposition = part.getDisposition();
		final String fileName = part.getFileName();
		final StringBuilder imageTextString = new StringBuilder();
		imageTextString.append("[Image]");
		imageTextString.append("[Inline]");
		imageTextString.append(contentType);
		imageTextString.append(fileName);
		partString = imageTextString.toString();
		final StringBuilder imageInfoLogString = new StringBuilder();
		imageInfoLogString.append("Image in body.. with name:: ");
		imageInfoLogString.append(fileName);
		imageInfoLogString.append(" disposition:: ");
		imageInfoLogString.append(disposition);
		imageInfoLogString.append("HTML file tag:: ");
		imageInfoLogString.append(partString);
		LOGGER.info(imageInfoLogString.toString());
	} else if (part.isMimeType("multipart/*")) {
		final Multipart multiPart = (Multipart) part.getContent();
		for (int i = 0; i < multiPart.getCount(); i++) {
			partString = getMailPartAsText(multiPart.getBodyPart(i));
		}
	}

	return partString;
}
 
開發者ID:kuzavas,項目名稱:ephesoft,代碼行數:32,代碼來源:MailUtil.java

示例11: parseFileName

import javax.mail.Part; //導入方法依賴的package包/類
@SuppressWarnings("WeakerAccess")
public static String parseFileName(@Nonnull final Part currentPart) {
	try {
		return currentPart.getFileName();
	} catch (final MessagingException e) {
		throw new MimeMessageParseException(MimeMessageParseException.ERROR_GETTING_FILENAME, e);
	}
}
 
開發者ID:bbottema,項目名稱:simple-java-mail,代碼行數:9,代碼來源:MimeMessageParser.java

示例12: handleInline

import javax.mail.Part; //導入方法依賴的package包/類
private static String handleInline(Part part, List attachments, boolean ignoreAttachments) throws MessagingException, IOException {
	String fileName = part.getFileName();
	if (fileName != null) {
		// this is an attachment
		if (ignoreAttachments == false) {
			handleAttachment(part, attachments);
		}
		return null;
	}
	// inline content
	if (part.isMimeType("text/*")) {
		return getText(part);
	} else {
		// binary inline content and no fileNameprovide
		// treat as attachemnt with unknow file name
		if (ignoreAttachments == false) {
			handleAttachment(part, attachments);
		}
		return null;
	}
}
 
開發者ID:trackplus,項目名稱:Genji,代碼行數:22,代碼來源:MailReader.java

示例13: handleAttachment

import javax.mail.Part; //導入方法依賴的package包/類
private static void handleAttachment(Part part, List<EmailAttachment> attachments) throws MessagingException {
	String fileName = part.getFileName();
	try {
		if (fileName != null) {
			fileName = MimeUtility.decodeText(fileName);
		} else {
			fileName = "binaryPart.dat";
		}
		attachments.add(createEmailAttachment(part, fileName));
	} catch (Exception e) {
		// just ignore
	}
}
 
開發者ID:trackplus,項目名稱:Genji,代碼行數:14,代碼來源:MailReader.java

示例14: getAttachedFileNames

import javax.mail.Part; //導入方法依賴的package包/類
protected String getAttachedFileNames(Part part) throws Exception {
    String fileNames = "";
    Object content = part.getContent();
    if (!(content instanceof Multipart)) {
        if (decryptMessage && part.getContentType() != null &&
                part.getContentType().equals(ENCRYPTED_CONTENT_TYPE)) {
            part = decryptPart((MimeBodyPart) part);
        }
        // non-Multipart MIME part ...
        // is the file name set for this MIME part? (i.e. is it an attachment?)
        if (part.getFileName() != null && !part.getFileName().equals("") && part.getInputStream() != null) {
            String fileName = part.getFileName();
            // is the file name encoded? (consider it is if it's in the =?charset?encoding?encoded text?= format)
            if (fileName.indexOf('?') == -1) {
                // not encoded  (i.e. a simple file name not containing '?')-> just return the file name
                return fileName;
            }
            // encoded file name -> remove any chars before the first "=?" and after the last "?="
            return fileName.substring(fileName.indexOf("=?"), fileName.length() -
                    ((new StringBuilder(fileName)).reverse()).indexOf("=?"));
        }
    } else {
        // a Multipart type of MIME part
        Multipart mpart = (Multipart) content;
        // iterate through all the parts in this Multipart ...
        for (int i = 0, n = mpart.getCount(); i < n; i++) {
            if (!"".equals(fileNames)) {
                fileNames += STR_COMMA;
            }
            // to the list of attachments built so far append the list of attachments in the current MIME part ...
            fileNames += getAttachedFileNames(mpart.getBodyPart(i));
        }
    }
    return fileNames;
}
 
開發者ID:CloudSlang,項目名稱:cs-actions,代碼行數:36,代碼來源:GetMailMessage.java

示例15: getAttachmentsOfMultipartMessage

import javax.mail.Part; //導入方法依賴的package包/類
/**
 * Returns an attachment list for a given Mime Multipart object.
 * 
 * @param mp the input Mime part of the email's content
 * @param level debug variable
 * @return list of files where the attachments are saved
 * @throws MessagingException
 * @throws IOException 
 */
private List<Attachment> getAttachmentsOfMultipartMessage(Multipart mp, boolean onlyInfo, int level) throws MessagingException, IOException {
  List<Attachment> files = new LinkedList<Attachment>();

  for (int j = 0; j < mp.getCount(); j++) {
    
    Part bp = mp.getBodyPart(j);
    String contentType = bp.getContentType().toLowerCase();
    
    if (!Part.ATTACHMENT.equalsIgnoreCase(bp.getDisposition())) {
      if (contentType.indexOf("multipart/") != -1) {
        files.addAll(getAttachmentsOfMultipartMessage((Multipart)(bp.getContent()), onlyInfo, level + 1));
      }
      continue;
    }
    String fName = bp.getFileName() == null ? "noname" : bp.getFileName();
    files.add(new Attachment(MimeUtility.decodeText(fName), bp.getSize()));
    if (!onlyInfo) {
      InputStream is = bp.getInputStream();
      File f = new File(this.attachmentFolder + bp.getFileName());
      FileOutputStream fos = new FileOutputStream(f);
      byte[] buf = new byte[4096];
      int bytesRead;
      while((bytesRead = is.read(buf))!=-1) {
          fos.write(buf, 0, bytesRead);
      }
      fos.close();
    }
    
  }
  
  return files;
}
 
開發者ID:k-kojak,項目名稱:yako,代碼行數:42,代碼來源:SimpleEmailMessageProvider.java


注:本文中的javax.mail.Part.getFileName方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。