javax.mail.internet.ContentType Java Examples

The following examples show how to use javax.mail.internet.ContentType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MimeMessageParser.java    From commons-email with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #2
Source File: MultipartMimeUtils.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the text content for a {@link BodyPart}, assuming the default
 * encoding.
 */
public static String getTextContent(BodyPart part) throws MessagingException, IOException {
  ContentType contentType = new ContentType(part.getContentType());
  String charset = contentType.getParameter("charset");
  if (charset == null) {
    // N.B.(schwardo): The MIME spec doesn't seem to provide a
    // default charset, but the default charset for HTTP is
    // ISO-8859-1.  That seems like a reasonable default.
    charset = "ISO-8859-1";
  }

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ByteStreams.copy(part.getInputStream(), baos);
  try {
    return new String(baos.toByteArray(), charset);
  } catch (UnsupportedEncodingException ex) {
    return new String(baos.toByteArray());
  }
}
 
Example #3
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #4
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #5
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #6
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #7
Source File: ClientSecretGet.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public void applyTo(final HTTPRequest httpRequest) {
    if (httpRequest.getMethod() != HTTPRequest.Method.GET)
        throw new SerializeException("The HTTP request method must be GET");

    ContentType ct = httpRequest.getContentType();
    if (ct == null)
        throw new SerializeException("Missing HTTP Content-Type header");

    if (! ct.match(CommonContentTypes.APPLICATION_URLENCODED))
        throw new SerializeException("The HTTP Content-Type header must be "
        + CommonContentTypes.APPLICATION_URLENCODED);

    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(toParameters());
    String queryString = URLUtils.serializeParameters(params);
    httpRequest.setQuery(queryString);
}
 
Example #8
Source File: DefaultReceiveEmailProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
private String getTextFromMimeMultipart( MimeMultipart mimeMultipart ) throws IOException, MessagingException
{

    int count = mimeMultipart.getCount();
    if ( count == 0 )
        throw new MessagingException( "Multipart with no body parts not supported." );

    boolean multipartAlt = new ContentType( mimeMultipart.getContentType() ).match( "multipart/alternative" );
    if ( multipartAlt )
        return getTextFromBodyPart( mimeMultipart.getBodyPart( count - 1 ) );

    String result = "";
    for ( int i = 0; i < count; i++ )
    {
        BodyPart bodyPart = mimeMultipart.getBodyPart( i );
        result += getTextFromBodyPart( bodyPart );
    }
    return result;
}
 
Example #9
Source File: ContentTypeCleaner.java    From eml-to-pdf-converter with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean isCompressed(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (logger.isTraceEnabled()) {
        try {
            logger.trace("Compression check.  MIME Base Content-Type:" + contentType.getBaseType());
            logger.trace("Compression check.  SMIME-TYPE:" + contentType.getParameter("smime-type"));
            logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + part.getDisposition());
        } catch (MessagingException e) {
            logger.trace("Compression check: no data available.");
        }
    }
    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("compressed-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for compressed data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for compressed data failed on BASE content type: " + baseType);
    }
    return false;
}
 
Example #11
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes the message content (if text/plain).
 */
public static void flowMessage(Message m, boolean delSp, int width) throws MessagingException, IOException {
    ContentType ct = new ContentType(m.getContentType());
    if (!ct.getBaseType().equals("text/plain")) {
        return;
    }
    String format = ct.getParameter("format");
    String text = format != null && format.equals("flowed") ? deflow(m) : (String) m.getContent();
    String coded = flow(text, delSp, width);
    ct.setParameter("format", "flowed");
    if (delSp) {
        ct.setParameter("delsp", "yes");
    }
    m.setContent(coded, ct.toString());
    m.saveChanges();
}
 
Example #12
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * If the message is <code>format=flowed</code> 
 * set the encoded version as message content.
 */
public static void deflowMessage(Message m) throws MessagingException, IOException {
    ContentType ct = new ContentType(m.getContentType());
    String format = ct.getParameter("format");
    if (ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed")) {
        String delSp = ct.getParameter("delsp");
        String deflowed = deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes"));
        
        ct.getParameterList().remove("format");
        ct.getParameterList().remove("delsp");
        
        if (ct.toString().contains("flowed")) {
            LOGGER.error("FlowedMessageUtils dind't remove the flowed correctly");
        }

        m.setContent(deflowed, ct.toString());
        m.saveChanges();
    }
}
 
Example #13
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
    }
    return false;
}
 
Example #14
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_noCharset() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html;"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #15
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_semicolonSequenceInParameterListAndColonInsteadOfEqualSign() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; ;;;; charset:\"utf-16\" ;;;;"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #16
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_quotedPrintable() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; charset=3Dutf-16"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #17
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_typeAndCharsetSomewherePlainAndCharsetAlias() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/plain; latin1"));

	assertThat("text/plain", equalToIgnoringCase(contentType.getBaseType()));
	assertThat("ISO-8859-1", equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #18
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_typeAndCharsetSomewhereHtml() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; utf-16"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #19
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_typeAndCharsetMissing() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "%%% text/html;"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #20
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_empty() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, ""));

	assertThat(ContentTypeCleaner.DEFAULT_BASETYPE, equalToIgnoringCase(contentType.getBaseType()));
	assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #21
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_unknownCharset() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; charset=ABCDEF"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #22
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_brokenContentType() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "BROKEN_STRING"));

	assertThat(ContentTypeCleaner.DEFAULT_BASETYPE, equalToIgnoringCase(contentType.getBaseType()));
	assertThat(ContentTypeCleaner.DEFAULT_CHARSET, equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #23
Source File: DataUriFetcher.java    From caja with Apache License 2.0 5 votes vote down vote up
private static String charsetFromMime(String mime) {
  String charset;
  try {
    ContentType parsedType = new ContentType(mime);
    charset = parsedType.getParameter("charset");
  } catch (ParseException e) {
    charset = null;
  }
  if (null == charset || "".equals(charset)) {
    return DATA_URI_DEFAULT_CHARSET;
  } else {
    return charset;
  }
}
 
Example #24
Source File: FetchedData.java    From caja with Apache License 2.0 5 votes vote down vote up
private static String getCharSet(URLConnection conn) {
  try {
    String contentType = conn.getContentType();
    if (contentType == null) { return ""; }
    String charset = new ContentType(contentType).getParameter("charset");
    return (charset == null) ? "" : charset;
  } catch (ParseException e) {
    return "";
  }
}
 
Example #25
Source File: FlowedMessageUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains the content of the encoded message, if previously encoded as <code>format=flowed</code>.
 */
public static String deflow(Message m) throws IOException, MessagingException {
    ContentType ct = new ContentType(m.getContentType());
    String format = ct.getParameter("format");
    if (ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed")) {
        String delSp = ct.getParameter("delsp");
        return deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes"));
        
    } else if (ct.getPrimaryType().equals("text")) {
        return (String) m.getContent();
    } else {
        return null;
    }
}
 
Example #26
Source File: ContentReplacer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private String getContentType(Mail mail, Optional<Charset> charset) throws MessagingException, ParseException {
    String contentTypeAsString = mail.getMessage().getContentType();
    if (charset.isPresent()) {
        ContentType contentType = new ContentType(contentTypeAsString);
        contentType.setParameter("charset", charset.get().name());
        return contentType.toString();
    }
    return contentTypeAsString;
}
 
Example #27
Source File: OnlyText.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static void setContentFromPart(Message m, Part p, String newText, boolean setTextPlain) throws MessagingException, IOException {
    String contentType = p.getContentType();
    if (setTextPlain) {
        ContentType ct = new ContentType(contentType);
        ct.setPrimaryType("text");
        ct.setSubType("plain");
        contentType = ct.toString();
    }
    m.setContent(newText != null ? newText : p.getContent(), contentType);
    String[] h = p.getHeader("Content-Transfer-Encoding");
    if (h != null && h.length > 0) {
        m.setHeader("Content-Transfer-Encoding", h[0]);
    }
    m.saveChanges();
}
 
Example #28
Source File: cfMAIL.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private void addAttachments( Enumeration<fileAttachment> _attach, Multipart _parent, boolean _isInline ) throws MessagingException{
	while ( _attach.hasMoreElements() ){
		fileAttachment nextFile = _attach.nextElement();
		FileDataSource fds 			= new FileDataSource( nextFile.getFilepath() );
		String mimeType = nextFile.getMimetype();
		if (mimeType == null){
			// if mime type not supplied then auto detect
			mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(nextFile.getFilepath());
     }else{
			// since mime type is not null then it the mime type has been set manually therefore
			// we need to ensure that any call to the underlying FileDataSource.getFileTypeMap()
			// returns a FileTypeMap that will map to this type
			fds.setFileTypeMap(new CustomFileTypeMap(mimeType));
		}
		
		String filename = cleanName(fds.getName());
		try {
			// encode the filename to ensure that it contains US-ASCII characters only
			filename = MimeUtility.encodeText( filename, "utf-8", "b" );
		} catch (UnsupportedEncodingException e5) {
			// shouldn't occur
		}
	  MimeBodyPart mimeAttach	= new MimeBodyPart();
	  mimeAttach.setDataHandler( new DataHandler(fds) );
		mimeAttach.setFileName( filename );

		ContentType ct = new ContentType(mimeType);
		ct.setParameter("name", filename );
		
		mimeAttach.setHeader("Content-Type", ct.toString() );

		if ( _isInline ){
       mimeAttach.setDisposition( "inline" );
       mimeAttach.addHeader( "Content-id", "<" + nextFile.getContentid() + ">" );
		}
     
		_parent.addBodyPart(mimeAttach);
	}
}
 
Example #29
Source File: ContentTypeCleanerTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cleanContentType_semicolonSequenceInParameterList() throws MessagingException {
	ContentType contentType = new ContentType(ContentTypeCleaner.cleanContentType(null, "text/html; ;;;; ;;;   charset=\"utf-16\"  ;;;;"));

	assertThat("text/html", equalToIgnoringCase(contentType.getBaseType()));
	assertThat("utf-16", equalToIgnoringCase(contentType.getParameter("charset")));
}
 
Example #30
Source File: text_plain.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private String getCharset(String type) {
try {
    ContentType ct = new ContentType(type);
    String charset = ct.getParameter("charset");
    if (charset == null)
	// If the charset parameter is absent, use US-ASCII.
	charset = "us-ascii";
    return MimeUtility.javaCharset(charset);
} catch (Exception ex) {
    return null;
}
   }