类javax.mail.internet.MimePart源码实例Demo

下面列出了怎么用javax.mail.internet.MimePart的API类实例代码及写法,或者点击链接到github查看源代码。


/**
 * Set the given text directly as content in non-multipart mode
 * or as default body part in multipart mode.
 * The "html" flag determines the content type to apply.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param text the text for the message
 * @param html whether to apply content type "text/html" for an
 * HTML mail, using default content type ("text/plain") else
 * @throws MessagingException in case of errors
 */
public void setText(String text, boolean html) throws MessagingException {
	Assert.notNull(text, "Text must not be null");
	MimePart partToUse;
	if (isMultipart()) {
		partToUse = getMainPart();
	}
	else {
		partToUse = this.mimeMessage;
	}
	if (html) {
		setHtmlTextToMimePart(partToUse, text);
	}
	else {
		setPlainTextToMimePart(partToUse, text);
	}
}
 

/**
 * Set the given text directly as content in non-multipart mode
 * or as default body part in multipart mode.
 * The "html" flag determines the content type to apply.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param text the text for the message
 * @param html whether to apply content type "text/html" for an
 * HTML mail, using default content type ("text/plain") else
 * @throws MessagingException in case of errors
 */
public void setText(String text, boolean html) throws MessagingException {
	Assert.notNull(text, "Text must not be null");
	MimePart partToUse;
	if (isMultipart()) {
		partToUse = getMainPart();
	}
	else {
		partToUse = this.mimeMessage;
	}
	if (html) {
		setHtmlTextToMimePart(partToUse, text);
	}
	else {
		setPlainTextToMimePart(partToUse, text);
	}
}
 
源代码3 项目: davmail   文件: ImapConnection.java

/**
 * Compute body part size with failover.
 * @param bodyPart MIME body part
 * @return body part size or 0 on error
 */
private int getBodyPartSize(MimePart bodyPart) {
    int bodySize = 0;
    try {
        bodySize = bodyPart.getSize();
        if (bodySize == -1) {
            // failover, try to get size
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bodyPart.writeTo(baos);
            bodySize = baos.size();
        }
    } catch (IOException | MessagingException e) {
        LOGGER.warn("Unable to get body part size " + e.getMessage(), e);
    }
    return bodySize;
}
 
源代码4 项目: ats-framework   文件: MimePackage.java

@PublicAtsApi
public List<InputStream> getAllStreams() throws PackageException {

    boolean storeReconnected = false;
    try {
        // store should be opened for actions including getting InputStream.
        storeReconnected = reconnectStoreIfClosed();
        ArrayList<InputStream> streams = new ArrayList<InputStream>();

        try {
            for (MimePart part : parts) {
                streams.add(part.getInputStream());
            }
        } finally {
            closeStoreConnection(storeReconnected);
        }
        return streams;

    } catch (MessagingException me) {
        throw new PackageException("Could not read mime parts", me);
    } catch (IOException ioe) {
        throw new PackageException("Could not read mime parts", ioe);
    }
}
 
源代码5 项目: ats-framework   文件: MimePackage.java

/**
 * Get the specified header value from a specified MIME part
 *
 * @param headerName
 * @param partNum
 * @param headerIndex
 * @return
 * @throws PackageException
 */
@PublicAtsApi
public String getPartHeader(
                             String headerName,
                             int partNum,
                             int headerIndex ) throws PackageException {

    try {
        String[] headers;
        if (partNum >= parts.size()) {
            throw new NoSuchMimePartException("No MIME part at position '" + partNum + "'");
        }

        MimePart part = parts.get(partNum);
        headers = part.getHeader(headerName);

        if ( (headers != null) && (headers.length > headerIndex)) {
            return headers[headerIndex];
        } else {
            throw new NoSuchHeaderException(headerName, partNum, headerIndex);
        }
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码6 项目: ats-framework   文件: MimePackage.java

/**
 * Get all header values from a specified MIME part
 *
 * @param headerName
 * @param partNum
 * @return
 * @throws PackageException
 */
@PublicAtsApi
public String[] getPartHeaderValues(
                                     String headerName,
                                     int partNum ) throws PackageException {

    try {
        String[] headers;
        if (partNum >= parts.size()) {
            throw new NoSuchMimePartException("No MIME part at position '" + partNum + "'");
        }

        MimePart part = parts.get(partNum);
        headers = part.getHeader(headerName);

        if ( (headers != null) && (headers.length > 0)) {
            return headers;
        } else {
            throw new NoSuchHeaderException(headerName, partNum);
        }
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码7 项目: ats-framework   文件: MimePackage.java

/**
 * Get a MIME part based on it's index and type
 *
 * @param partIndex
 *            the index of the MIME part
 * @param isAttachment
 *            the type - true if the part is attachment, false otherwise
 * @return the mime part
 * @throws NoSuchMimePartException
 *             if there is no such part
 */
@PublicAtsApi
public MimePart getPart(
                         int partIndex,
                         boolean isAttachment ) throws NoSuchMimePartException {

    // first check if there is part at this position at all
    if (isAttachment) {
        if (partIndex >= attachmentPartIndices.size()) {
            throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
        }
    } else {
        if (partIndex >= regularPartIndices.size()) {
            throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
        }
    }

    MimePart part;
    if (isAttachment) {
        part = getPart(attachmentPartIndices.get(partIndex));
    } else {
        part = getPart(regularPartIndices.get(partIndex));
    }

    return part;
}
 
源代码8 项目: ats-framework   文件: MimePackage.java

/**
 * Get the content type of a regular part
 *
 * @param partIndex
 *            the index of the regular part
 * @return the content type as string
 * @throws PackageException
 */
@PublicAtsApi
public String getRegularPartContentType(
                                         int partIndex ) throws PackageException {

    // first check if there is part at this position at all
    if (partIndex >= regularPartIndices.size()) {
        throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
    }

    try {
        MimePart part = getPart(regularPartIndices.get(partIndex));

        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getBaseType();
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码9 项目: ats-framework   文件: MimePackage.java

/**
 * Get the character set of a regular part
 *
 * @param partIndex
 *            the index of the part
 * @return the charset
 * @throws PackageException
 */
@PublicAtsApi
public String getRegularPartCharset(
                                     int partIndex ) throws PackageException {

    // first check if there is part at this position at all
    if (partIndex >= regularPartIndices.size()) {
        throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'");
    }

    try {
        MimePart part = getPart(regularPartIndices.get(partIndex));

        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getParameter("charset");
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码10 项目: ats-framework   文件: MimePackage.java

/**
 * Set/modify attachment file name
 *
 * @param attachmentPartIndex index among attachment parts only
 * @param fileName the file name. Add one or reset existing one
 * @throws NoSuchMimePartException if not such attachment part is found
 * @throws PackageException in case of other mail messaging exception
 */
@PublicAtsApi
public void setAttachmentFileName(
                                   int attachmentPartIndex,
                                   String fileName ) throws PackageException {

    // first check if there is part at this position at all
    if (attachmentPartIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + attachmentPartIndex + "'");
    }

    try {
        MimePart part = getPart(attachmentPartIndices.get(attachmentPartIndex));

        // set the attachment file name
        part.setFileName(fileName);
        // must save now
        this.message.saveChanges();
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码11 项目: ats-framework   文件: MimePackage.java

/**
 * Get an attachment's file name
 *
 * @param partIndex
 * @return
 * @throws PackageException
 */
@PublicAtsApi
public String getAttachmentFileName(
                                     int partIndex ) throws PackageException {

    // first check if there is part at this position at all
    if (partIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
    }

    try {
        MimePart part = getPart(attachmentPartIndices.get(partIndex));

        // get the attachment file name
        String fileName = part.getFileName();
        if (fileName == null) {
            throw new PackageException("Could not determine file name for attachment at position "
                                       + partIndex);
        }

        return fileName;

    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码12 项目: ats-framework   文件: MimePackage.java

/**
 * Get the attachment content type
 *
 * @param partIndex
 * @return
 * @throws PackageException
 */
@PublicAtsApi
public String getAttachmentContentType(
                                        int partIndex ) throws PackageException {

    // first check if there is part at this position at all
    if (partIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
    }

    try {
        MimePart part = getPart(attachmentPartIndices.get(partIndex));

        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getBaseType();
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码13 项目: ats-framework   文件: MimePackage.java

/**
 * Get the attachment character set
 *
 * @param partIndex
 *            the index of the attachment
 * @return the character set for this attachment, null if there is no such
 * @throws PackageException
 */
@PublicAtsApi
public String getAttachmentCharset(
                                    int partIndex ) throws PackageException {

    // first check if there is part at this position at all
    if (partIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
    }

    try {
        MimePart part = getPart(attachmentPartIndices.get(partIndex));

        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getParameter("charset");
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码14 项目: ats-framework   文件: MimePackage.java

/**
 * Return the attachment data
 *
 * @param partIndex
 *            the index of the attachment
 * @return an InputStream with the attachment data
 * @throws PackageException
 */
@PublicAtsApi
public InputStream getAttachmentPartData(
                                          int partIndex ) throws PackageException {

    try {
        boolean storeReconnected = reconnectStoreIfClosed();
        // store should be opened for actions including getting InputStream. Hence store open is not in getPart
        try {
            MimePart part = getPart(partIndex, true);
            return part.getInputStream();
        } finally {
            closeStoreConnection(storeReconnected);
        }
    } catch (MessagingException me) {
        throw new PackageException("Error getting attachment data for part " + partIndex, me);
    } catch (IOException ioe) {
        throw new PackageException("Error getting attachment data for part " + partIndex, ioe);
    }
}
 
源代码15 项目: ats-framework   文件: Test_MimePackage.java

@Test
public void setBody_multiParts_with_textPart_only() throws Exception {

    // create a new message and add TEXT part to it
    MimePackage newMailMessage = new MimePackage();
    newMailMessage.addPart("text plain body", MimePackage.PART_TYPE_TEXT_PLAIN);

    MimePart textPart = newMailMessage.getPart(0, false);
    assertEquals(textPart.getContent(), "text plain body");
    assertEquals(textPart.getContentType(), "text/plain; charset=us-ascii");

    // modify the only part
    newMailMessage.setBody("new body");

    // verify the modifications
    MimePart newTextPart = newMailMessage.getPart(0, false);
    assertEquals(newTextPart.getContent(), "new body");
    assertEquals(newTextPart.getContentType(), "text/plain; charset=us-ascii");

    // verify there are no more parts
    try {
        newMailMessage.getPart(1, false);
        assertTrue("There is more than 1 part, while we expect to have just 1", false);
    } catch (NoSuchMimePartException e) {}
}
 
源代码16 项目: ats-framework   文件: Test_MimePackage.java

@Test
public void setBody_multiParts_with_htmlPart_only() throws Exception {

    // create a new message and add HTML part to it
    MimePackage newMailMessage = new MimePackage();
    newMailMessage.addPart("html body", MimePackage.PART_TYPE_TEXT_HTML);

    MimePart htmlPart = newMailMessage.getPart(0, false);
    assertEquals(htmlPart.getContent(), "html body");
    assertEquals(htmlPart.getContentType(), "text/html; charset=us-ascii");

    // modify the only part
    newMailMessage.setBody("new body");

    // verify the modifications
    MimePart newHtmlPart = newMailMessage.getPart(0, false);
    assertEquals(newHtmlPart.getContent(), "new body");
    assertEquals(newHtmlPart.getContentType(), "text/html; charset=us-ascii");

    // verify there are no more parts
    try {
        newMailMessage.getPart(1, false);
        assertTrue("There is more than 1 part, while we expect to have just 1", false);
    } catch (NoSuchMimePartException e) {}
}
 
源代码17 项目: lams   文件: MimeMessageHelper.java

/**
 * Set the given text directly as content in non-multipart mode
 * or as default body part in multipart mode.
 * The "html" flag determines the content type to apply.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param text the text for the message
 * @param html whether to apply content type "text/html" for an
 * HTML mail, using default content type ("text/plain") else
 * @throws MessagingException in case of errors
 */
public void setText(String text, boolean html) throws MessagingException {
	Assert.notNull(text, "Text must not be null");
	MimePart partToUse;
	if (isMultipart()) {
		partToUse = getMainPart();
	}
	else {
		partToUse = this.mimeMessage;
	}
	if (html) {
		setHtmlTextToMimePart(partToUse, text);
	}
	else {
		setPlainTextToMimePart(partToUse, text);
	}
}
 

/**
 * Set the given text directly as content in non-multipart mode
 * or as default body part in multipart mode.
 * The "html" flag determines the content type to apply.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param text the text for the message
 * @param html whether to apply content type "text/html" for an
 * HTML mail, using default content type ("text/plain") else
 * @throws MessagingException in case of errors
 */
public void setText(String text, boolean html) throws MessagingException {
	Assert.notNull(text, "Text must not be null");
	MimePart partToUse;
	if (isMultipart()) {
		partToUse = getMainPart();
	}
	else {
		partToUse = this.mimeMessage;
	}
	if (html) {
		setHtmlTextToMimePart(partToUse, text);
	}
	else {
		setPlainTextToMimePart(partToUse, text);
	}
}
 

/**
 * Attempt to repair the given contentType if broken.
 * @param mp Mimepart holding the contentType
 * @param contentType ContentType
 * @return fixed contentType String
 * @throws MessagingException
 */
public static String cleanContentType(MimePart mp, String contentType) throws MessagingException {
	ContentType ct = parseContentType(contentType);

	if (ct == null) {
		ct = getParsableContentType(contentType);
	}

	if (ct.getBaseType().equalsIgnoreCase("text/plain") || ct.getBaseType().equalsIgnoreCase("text/html")) {
		Charset charset = parseCharset(ct);
		if (charset == null) {
			Logger.debug("Charset of the ContentType could not be read, try to decode the contentType as quoted-printable");

			ContentType ctTmp = decodeContentTypeAsQuotedPrintable(contentType);
			if (parseCharset(ctTmp) != null) {
				ct = ctTmp;
			} else {
				ct.setParameter("charset", ContentTypeCleaner.DEFAULT_CHARSET);
			}
		}
	}

	return ct.toString();
}
 
源代码20 项目: ogham   文件: MultiContentHandler.java

@Override
public void setContent(MimePart message, Multipart multipart, Email email, Content content) throws ContentHandlerException {
	try {
		MultiContent multiContent = (MultiContent) content;
		MimeMultipart mp = new MimeMultipart("alternative");
		for (Content c : multiContent.getContents()) {
			delegate.setContent(message, mp, email, c);
		}
		// add the part
		MimeBodyPart part = new MimeBodyPart();
		part.setContent(mp);
		multipart.addBodyPart(part);
	} catch (MessagingException e) {
		throw new ContentHandlerException("Failed to generate alternative content", content, e);
	}
}
 
源代码21 项目: james-project   文件: Converter7Bit.java

private void convertPart(MimePart part) throws MessagingException, IOException {
    if ("8bit".equals(part.getEncoding())) {
        // The content may already be in encoded the form (likely with mail
        // created from a
        // stream). In that case, just changing the encoding to
        // quoted-printable will mangle
        // the result when this is transmitted. We must first convert the
        // content into its
        // native format, set it back, and only THEN set the transfer
        // encoding to force the
        // content to be encoded appropriately.

        // if the part doesn't contain text it will be base64 encoded.
        String contentTransferEncoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";
        part.setContent(part.getContent(), part.getContentType());
        part.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to "
            + contentTransferEncoding + " by " + mailetContext.getServerInfo());
    } else if (part.isMimeType("multipart/*")) {
        MultipartUtil.retrieveBodyParts((MimeMultipart) part.getContent())
            .forEach(Throwing.consumer(bodyPart -> convertPart((MimePart) bodyPart)));
    }
}
 
源代码22 项目: commons-email   文件: MimeMessageParser.java

/**
 * Checks whether the MimePart contains an object of the given mime type.
 *
 * @param part     the current MimePart
 * @param mimeType the mime type to check
 * @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private boolean isMimeType(final MimePart part, final String mimeType)
    throws MessagingException, IOException
{
    // Do not use part.isMimeType(String) as it is broken for MimeBodyPart
    // and does not really check the actual content type.

    try
    {
        final ContentType ct = new ContentType(part.getDataHandler().getContentType());
        return ct.match(mimeType);
    }
    catch (final ParseException ex)
    {
        return part.getContentType().equalsIgnoreCase(mimeType);
    }
}
 

private void setPlainTextToMimePart(MimePart mimePart, String text) throws MessagingException {
	if (getEncoding() != null) {
		mimePart.setText(text, getEncoding());
	}
	else {
		mimePart.setText(text);
	}
}
 

private void setHtmlTextToMimePart(MimePart mimePart, String text) throws MessagingException {
	if (getEncoding() != null) {
		mimePart.setContent(text, CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + getEncoding());
	}
	else {
		mimePart.setContent(text, CONTENT_TYPE_HTML);
	}
}
 

private void setPlainTextToMimePart(MimePart mimePart, String text) throws MessagingException {
	if (getEncoding() != null) {
		mimePart.setText(text, getEncoding());
	}
	else {
		mimePart.setText(text);
	}
}
 

private void setHtmlTextToMimePart(MimePart mimePart, String text) throws MessagingException {
	if (getEncoding() != null) {
		mimePart.setContent(text, CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + getEncoding());
	}
	else {
		mimePart.setContent(text, CONTENT_TYPE_HTML);
	}
}
 
源代码27 项目: FairEmail   文件: MimeUtil.java

/**
    * If a Content-Type handler has been specified,
    * call it to clean up the Content-Type value.
    *
    * @param	mp	the MimePart
    * @param	contentType	the Content-Type value
    * @return		the cleaned Content-Type value
    */
   public static String cleanContentType(MimePart mp, String contentType) {
if (cleanContentType != null) {
    try {
	return (String)cleanContentType.invoke(null,
				    new Object[] { mp, contentType });
    } catch (Exception ex) {
	return contentType;
    }
} else
    return contentType;
   }
 
源代码28 项目: ats-framework   文件: MimePackage.java

private boolean isPartAttachment(
                                  MimePart part ) throws PackageException {

    try {
        String disposition = part.getDisposition();
        if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            return true;
        }
    } catch (MessagingException me) {
        throw new PackageException("Could not determine if part is an attachment", me);
    }

    return false;
}
 
源代码29 项目: ats-framework   文件: MimePackage.java

private MimePart getPart(
                          int index ) throws NoSuchMimePartException {

    if (index >= parts.size()) {
        throw new NoSuchMimePartException("No MIME part at position '" + index + "'");
    }

    MimePart part = this.parts.get(index);
    if (part != null) {
        return part;
    } else {
        throw new NoSuchMimePartException("No part at position '" + index + "'");
    }
}
 
源代码30 项目: ats-framework   文件: Test_MimePackage.java

@Test
public void setBody_multiParts_with_textAndHtmlParts() throws Exception {

    // create a new message and add TEXT and HTML parts to it
    MimePackage newMailMessage = new MimePackage();
    newMailMessage.addPart("text plain body", MimePackage.PART_TYPE_TEXT_PLAIN);
    newMailMessage.addPart("html body", MimePackage.PART_TYPE_TEXT_HTML);

    MimePart textPart = newMailMessage.getPart(0, false);
    assertEquals(textPart.getContent(), "text plain body");
    assertEquals(textPart.getContentType(), "text/plain; charset=us-ascii");

    MimePart htmlPart = newMailMessage.getPart(1, false);
    assertEquals(htmlPart.getContent(), "html body");
    assertEquals(htmlPart.getContentType(), "text/html; charset=us-ascii");

    // modify both parts
    newMailMessage.setBody("new body");

    // verify the modifications
    MimePart newTextPart = newMailMessage.getPart(0, false);
    assertEquals(newTextPart.getContent(), "new body");
    assertEquals(newTextPart.getContentType(), "text/plain; charset=us-ascii");

    MimePart newHtmlPart = newMailMessage.getPart(1, false);
    assertEquals(newHtmlPart.getContent(), "new body");
    assertEquals(newHtmlPart.getContentType(), "text/html; charset=us-ascii");

    // verify there are no more parts
    try {
        newMailMessage.getPart(2, false);
        assertTrue("There is more than 2 parts, while we expect to have just 2", false);
    } catch (NoSuchMimePartException e) {}
}
 
 类所在包
 同包方法