javax.mail.internet.ParseException Java Examples

The following examples show how to use javax.mail.internet.ParseException. 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: HttpImporter.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private static String fromContentDisposition ( final String field )
{
    if ( field == null || field.isEmpty () )
    {
        return null;
    }

    try
    {
        final ContentDisposition cd = new ContentDisposition ( field );
        return cd.getParameter ( "filename" );
    }
    catch ( final ParseException e )
    {
        return null;
    }
}
 
Example #2
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 #3
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 #4
Source File: EmailTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendBadHostName()
{
    try
    {
        getMailServer();

        email = new MockEmailConcrete();
        email.setSubject("Test Email #1 Subject");
        email.setHostName("bad.host.com");
        email.setFrom("[email protected]");
        email.addTo("[email protected]");
        email.addCc("[email protected]");
        email.addBcc("[email protected]");
        email.addReplyTo("[email protected]");

        email.setContent(
                "test string object",
                " ; charset=" + EmailConstants.US_ASCII);

        email.send();
        fail("Should have thrown an exception");
    }
    catch (final EmailException e)
    {
        assertTrue(e.getCause() instanceof ParseException);
        fakeMailServer.stop();
    }
}
 
Example #5
Source File: MailImpl.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Read the MailImpl from an <code>ObjectInputStream</code>.
 *
 * @param in the ObjectInputStream from which the object is read
 * @throws IOException            if an error occurs while reading from the stream
 * @throws ClassNotFoundException ?
 * @throws ClassCastException     if the serialized objects are not of the appropriate type
 */
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {
        Object obj = in.readObject();
        if (obj == null) {
            sender = null;
        } else if (obj instanceof String) {
            sender = new MailAddress((String) obj);
        } else if (obj instanceof MailAddress) {
            sender = (MailAddress) obj;
        }
    } catch (ParseException pe) {
        throw new IOException("Error parsing sender address: " + pe.getMessage());
    }
    recipients = (Collection<MailAddress>) in.readObject();
    state = (String) in.readObject();
    errorMessage = (String) in.readObject();
    name = (String) in.readObject();
    remoteHost = (String) in.readObject();
    remoteAddr = (String) in.readObject();
    setLastUpdated((Date) in.readObject());
    try {
        setAttributesUsingJsonable(in);
    } catch (Exception e) {
        setAttributesUsingJavaSerializable(in);
    }
    perRecipientSpecificHeaders = (PerRecipientHeaders) in.readObject();
}
 
Example #6
Source File: Account.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the recipient.
 * 
 * @param recipient
 *            The recipient to set
 */
protected void setRecipient(String recipient) throws ConfigurationException {
    if (null == recipient) {
        fieldRecipient = null;
        return;
    }

    try {
        setRecipient(new MailAddress(recipient));
    } catch (ParseException pe) {
        throw new ConfigurationException("Invalid recipient address specified: " + recipient);
    }
}
 
Example #7
Source File: ParsedConfiguration.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the blacklist.
 * 
 * @param blacklistValue
 *            The blacklist to set
 */
protected void setBlacklist(String blacklistValue) throws ConfigurationException {
    StringTokenizer st = new StringTokenizer(blacklistValue, ", \t", false);
    Set<MailAddress> blacklist = new HashSet<>();
    String token = null;
    while (st.hasMoreTokens()) {
        try {
            token = st.nextToken();
            blacklist.add(new MailAddress(token));
        } catch (ParseException pe) {
            throw new ConfigurationException("Invalid blacklist mail address specified: " + token);
        }
    }
    setBlacklist(blacklist);
}
 
Example #8
Source File: MessageProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Method handleParseException.
 *
 * @param ex
 * @throws MessagingException
 */
protected void handleParseException(ParseException ex) throws MessagingException {
    // Update the flags of the received message
    if (!isLeaveUndeliverable()) {
        setMessageDeleted();
    }
    if (isMarkUndeliverableSeen()) {
        setMessageSeen();
    }
    logStatusWarn("Message could not be delivered due to an error parsing a mail address.");
    LOGGER.debug("UNDELIVERABLE Message ID: {}", getMessageIn().getMessageID(), ex);
}
 
Example #9
Source File: SpecialAddressesUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Set<MailAddress> getReplyTos(InternetAddress[] replyToArray) {
    ImmutableSet.Builder<MailAddress> builder = ImmutableSet.builder();
    for (InternetAddress replyTo : replyToArray) {
        try {
            builder.add(new MailAddress(replyTo));
        } catch (ParseException pe) {
            LOGGER.warn("Unable to parse a \"REPLY_TO\" header address in the original message: {}; ignoring.", replyTo);
        }
    }
    return builder.build();
}
 
Example #10
Source File: FakeMail.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Read the FakeMail from an <code>ObjectInputStream</code>.
 */
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {
        Object obj = in.readObject();
        if (obj == null) {
            sender = null;
        } else if (obj instanceof String) {
            sender = new MailAddress((String) obj);
        } else if (obj instanceof MailAddress) {
            sender = (MailAddress) obj;
        }
    } catch (ParseException pe) {
        throw new IOException("Error parsing sender address: " + pe.getMessage());
    }
    recipients = (Collection<MailAddress>) in.readObject();
    state = (String) in.readObject();
    errorMessage = (String) in.readObject();
    name = (String) in.readObject();
    remoteHost = (String) in.readObject();
    remoteAddr = (String) in.readObject();
    setLastUpdated((Date) in.readObject());
    // the following is under try/catch to be backwards compatible
    // with messages created with James version <= 2.2.0a8
    try {
        setAttributesRaw((Map<String, Object>) in.readObject());
    } catch (OptionalDataException ode) {
        if (ode.eof) {
            attributes = new HashMap<>();
        } else {
            throw ode;
        }
    }
    perRecipientHeaders = (PerRecipientHeaders) in.readObject();
}
 
Example #11
Source File: AbstractSign.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method that checks if there is at least one address in the "From:" header
 * same as the <i>reverse-path</i>.
 * @param mail The mail to check.
 * @return True if an address is found, false otherwise.
 */    
protected final boolean fromAddressSameAsReverse(Mail mail) {
    
    if (!mail.hasSender()) {
        return false;
    }
    MailAddress reversePath = mail.getMaybeSender().get();
    
    try {
        InternetAddress[] fromArray = (InternetAddress[]) mail.getMessage().getFrom();
        if (fromArray != null) {
            for (InternetAddress aFromArray : fromArray) {
                MailAddress mailAddress;
                try {
                    mailAddress = new MailAddress(aFromArray);
                } catch (ParseException pe) {
                    LOGGER.info("Unable to parse a \"FROM\" header address: {}; ignoring.", aFromArray);
                    continue;
                }
                if (mailAddress.equals(reversePath)) {
                    return true;
                }
            }
        }
    } catch (MessagingException me) {
        LOGGER.info("Unable to parse the \"FROM\" header; ignoring.");
    }
    
    return false;
    
}
 
Example #12
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 #13
Source File: ContentReplacer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private boolean applyBodyReplacingUnits(Mail mail, ReplaceConfig replaceConfig, Optional<Charset> charset) throws IOException, MessagingException, ParseException {
    if (!replaceConfig.getBodyReplacingUnits().isEmpty()) {
        Object bodyObj = mail.getMessage().getContent();
        if (bodyObj instanceof String) {
            String body = applyPatterns(replaceConfig.getBodyReplacingUnits(), 
                    Strings.nullToEmpty((String) bodyObj));
            setContent(mail, body, charset);
            return true;
        }
    }
    return false;
}
 
Example #14
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 #15
Source File: ContentTypeCleaner.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the contentType can be parsed. If not return a fixed version.
 * When thats not possible return a default contentType string.
 * @param contentType
 * @return Fixed contentType string or default
 * @throws ParseException
 */
private static ContentType getParsableContentType(String contentType) throws ParseException {
	Logger.debug("Encountered an unparsable contenttype, try to fix it.");

	// we can't fix an empty contentType, fallback to default
	if (Strings.isNullOrEmpty(contentType)) {
		Logger.debug("ContentType empty, fallback to \"%s\"", DEFAULT_CONTENTTYPE);
		return new ContentType(DEFAULT_CONTENTTYPE);
	}

	ContentType tmp = parseContentType(fixContentType_semicolonSequenceInParams(contentType));
	if (tmp != null) {
		Logger.debug("Fix succeeded (1)");
		return tmp;
	}

	tmp = parseContentType(fixContentType_colonAsParamDelim(contentType));
	if (tmp != null) {
		Logger.debug("Fix succeeded (2)");
		return tmp;
	}

	// Neither did work, lets try to use clean1 and clean2 in conjunction
	tmp = parseContentType(fixContentType_semicolonSequenceInParams(fixContentType_colonAsParamDelim(contentType)));
	if (tmp != null) {
		Logger.debug("Fix succeeded (1&2)");
		return tmp;
	}

	// this is a rather desperate approach but lets try it nevertheless
	tmp = parseContentType(fixContentType_findByBruteForce(contentType));
	if (tmp != null) {
		Logger.debug("Fix succeeded (3)");
		return tmp;
	}

	Logger.debug("Encountered broken ContentType, fallback to default: %s", DEFAULT_CONTENTTYPE);
	return new ContentType(DEFAULT_CONTENTTYPE);
}
 
Example #16
Source File: ContentTypeCleaner.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
/**
 * Try to parse the given contentType String into a ContentType instance.
 * @param contentType
 * @return new ContentType instance, or null if not parsable
 */
private static ContentType parseContentType(String contentType) {
	try {
		return new ContentType(contentType);
	} catch (ParseException e) {
		return null;
	}
}
 
Example #17
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String extractPayloadFilename() throws ParseException {
    String s = getContentDisposition();
    if (s == null || s.length() < 1) {
        return null;
    }
    // TODO: This should be a case insensitive lookup per RFC6266
    String tmpFilename = null;

    ContentDisposition cd = new ContentDisposition(s);
    tmpFilename = cd.getParameter("filename");

    if (tmpFilename == null || tmpFilename.length() < 1) {
        /* Try to extract manually */
        int n = s.indexOf("filename=");
        if (n > -1) {
            tmpFilename = s.substring(n);
            tmpFilename = tmpFilename.replaceFirst("filename=", "");

            int n1 = tmpFilename.indexOf(",");
            if (n1 > -1) {
                s = s.substring(0, n1 - 1);
            }
            tmpFilename = tmpFilename.replaceAll("\"", "");
            s = s.trim();
        } else {
            /* Try just using file separator */
            int pos = s.lastIndexOf(File.separator);
            if (pos >= 0) {
                tmpFilename = s.substring(pos + 1);
            }
        }
    }
    return tmpFilename;
}
 
Example #18
Source File: ContentDispositionParserTest.java    From email-mime-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void getContentDispositionFileName() throws ParseException, MimeException, IOException{		
	setDispositionDecodedFilename().assertDecodedFileString(getPlainTextCheckSum());		
}
 
Example #19
Source File: ContentReplacer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void setContent(Mail mail, String body, Optional<Charset> charset) throws MessagingException, ParseException {
    mail.getMessage().setContent(body, getContentType(mail, charset));
}
 
Example #20
Source File: MessageParameters.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public String getParameter(String key) throws InvalidParameterException {
    StringTokenizer keyParts = new StringTokenizer(key, ".", false);

    if (keyParts.countTokens() != 2) {
        throw new InvalidParameterException("Invalid key format", this, key, null);
    }

    String area = keyParts.nextToken();
    String areaID = keyParts.nextToken();

    if (area.equals(KEY_SENDER)) {
        return getTarget().getPartnership().getSenderID(areaID);
    } else if (area.equals(KEY_RECEIVER)) {
        return getTarget().getPartnership().getReceiverID(areaID);
    } else if (area.equals(KEY_ATTRIBUTES)) {
        return getTarget().getAttribute(areaID);
    } else if (area.equals(KEY_HEADERS)) {
        return getTarget().getHeader(areaID);
    } else if (area.equals(KEY_CONTENT_FILENAME) && areaID.equals("filename")) {
        String s = null;
        try {
            s = getTarget().extractPayloadFilename();
        } catch (ParseException e) {
            logger.warn("Failed to extract filename from content-disposition: " + org.openas2.logging.Log.getExceptionMsg(e), e);
        }
        if (s == null || s.length() < 1) {
            s = getTarget().getPayloadFilename();
        }
        if (s != null && s.length() > 0) {
            return s;
        }
        // If it gets to here then the sender did not send a filename so...
        String filename = Properties.getProperty(Properties.AS2_RX_MESSAGE_FILENAME_FALLBACK, null);
        if (filename == null) {
            return getTarget().getMessageID();
        } else {
            CompositeParameters parser = new CompositeParameters(false).add("date", new DateParameters()).add("msg", new MessageParameters(getTarget())).add("rand", new RandomParameters());
            return ParameterParser.parse(filename, parser);
        }
    } else {
        throw new InvalidParameterException("Invalid area in key", this, key, null);
    }
}
 
Example #21
Source File: DataHistoryItem.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void readObject(java.io.ObjectInputStream in) throws ParseException, IOException, ClassNotFoundException {
    contentType = new ContentType((String) in.readObject());

    attributes = (Map<String, String>) in.readObject();
}
 
Example #22
Source File: DataHistoryItem.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setContentType(String type) throws ParseException {
    setContentType(new ContentType(type));
}
 
Example #23
Source File: DataHistoryItem.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public DataHistoryItem(String contentType) throws ParseException {
    super();
    setContentType(contentType);
}
 
Example #24
Source File: ContentDispositionParserTest.java    From email-mime-parser with Apache License 2.0 4 votes vote down vote up
private ContentDispositionParserTest setDispositionDecodedFilename() throws ParseException, MimeException {
	fileName = ContentDispositionDecoder.decodeDispositionFileName(getEncodedContentDispositionMap());
	return this;
}
 
Example #25
Source File: Message.java    From OpenAs2App with BSD 2-Clause "Simplified" License votes vote down vote up
String extractPayloadFilename() throws ParseException;