javax.mail.Header Java Examples

The following examples show how to use javax.mail.Header. 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: BaseMessageMDN.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("MDN From:").append(getPartnership().getReceiverIDs());
    buf.append("To:").append(getPartnership().getSenderIDs());

    Enumeration<Header> headerEn = getHeaders().getAllHeaders();
    buf.append(System.getProperty("line.separator") + "Headers:{");

    while (headerEn.hasMoreElements()) {
        Header header = headerEn.nextElement();
        buf.append(header.getName()).append("=").append(header.getValue());

        if (headerEn.hasMoreElements()) {
            buf.append(", ");
        }
    }

    buf.append("}");
    buf.append(System.getProperty("line.separator") + "Attributes:").append(getAttributes());
    buf.append(System.getProperty("line.separator") + "Text: " + System.getProperty("line.separator"));
    buf.append(getText()).append(System.getProperty("line.separator"));

    return buf.toString();
}
 
Example #2
Source File: RMetadataUtils.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses metadata stored in a Debian Control File-like format.
 *
 * @see <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file">Description File</a>
 */
public static Map<String, String> parseDescriptionFile(final InputStream in) {
  checkNotNull(in);
  try {
    LinkedHashMap<String, String> results = new LinkedHashMap<>();
    InternetHeaders headers = new InternetHeaders(in);
    Enumeration headerEnumeration = headers.getAllHeaders();
    while (headerEnumeration.hasMoreElements()) {
      Header header = (Header) headerEnumeration.nextElement();
      String name = header.getName();
      String value = header.getValue()
          .replace("\r\n", "\n")
          .replace("\r", "\n"); // TODO: "should" be ASCII only, otherwise need to know encoding?
      results.put(name, value); // TODO: Supposedly no duplicates, is this true?
    }
    return results;
  } catch (MessagingException e) {
    throw new RException(null, e);
  }
}
 
Example #3
Source File: RelayLimit.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws javax.mail.MessagingException {
    MimeMessage mm = mail.getMessage();
    int count = 0;
    for (Enumeration<Header> e = mm.getAllHeaders(); e.hasMoreElements();) {
        Header hdr = e.nextElement();
        if (hdr.getName().equals(RFC2822Headers.RECEIVED)) {
            count++;
        }
    }
    if (count >= limit) {
        return mail.getRecipients();
    } else {
        return null;
    }
}
 
Example #4
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked")
@PublicAtsApi
public List<PackageHeader> getAllHeaders() throws PackageException {

    try {
        List<PackageHeader> headers = new ArrayList<PackageHeader>();

        Enumeration<Header> messageHeaders = message.getAllHeaders();
        while (messageHeaders.hasMoreElements()) {
            Header messageHeader = messageHeaders.nextElement();
            headers.add(new PackageHeader(messageHeader.getName(), messageHeader.getValue()));
        }

        return headers;

    } 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
private String addHeadersTrace(
                                Enumeration<?> headers,
                                String level ) {

    final String level1 = level;
    final String level2 = "\t" + level1;
    final String prefix = getPrefixTrace(level1, "HEADERS START: ");

    StringBuilder headersString = new StringBuilder();

    boolean hasHeaders = headers.hasMoreElements();
    if (hasHeaders) {
        headersString.append(level1 + "HEADERS START:\n");
        while (headers.hasMoreElements()) {
            Header header = (Header) headers.nextElement();
            headersString.append(level2 + header.getName() + ": "
                                 + normalizeNewLinesTrace(prefix, header.getValue()) + "\n");
        }
        headersString.append(level1 + "HEADERS END:\n");
    }

    return headersString.toString();
}
 
Example #6
Source File: EmailToMimeMessageValidators.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
public void validateCustomHeaders(final Email email, final MimeMessage sentMessage)
        throws MessagingException, IOException {
    Map<String, String> customHeaders = email.getCustomHeaders();
    List<Header> internetHeaders = (List<Header>) Collections.list(sentMessage.getAllHeaders());
    List<String> headerKeys = internetHeaders.stream().map(Header::getName).collect(toList());

    assertions.assertThat(headerKeys)
            .as("Should contains all the headers keys provided at construction time")
            .containsAll(customHeaders.keySet());

    customHeaders.entrySet().stream()
            .forEach(entry -> {
                try {
                    assertions.assertThat(sentMessage.getHeader(entry.getKey())).isNotNull().containsExactly(entry.getValue());
                } catch (MessagingException e) {
                }
            });
}
 
Example #7
Source File: SMTPHandler.java    From holdmail with Apache License 2.0 6 votes vote down vote up
protected MessageHeaders getHeaders(MimeMessage message) throws MessagingException {

        Map<String, String> headerMap = new HashMap<>();

        // oh wow 2015 and it's untyped and uses Enumeration
        Enumeration allHeaders = message.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            Header header = (Header) allHeaders.nextElement();
            String headerName = header.getName();
            String headerVal = header.getValue();

            headerMap.put(headerName, headerVal);

        }

        return new MessageHeaders(headerMap);
    }
 
Example #8
Source File: SieveMailAdapter.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getHeaderNames() throws SieveMailException {
    Set<String> headerNames = new HashSet<>();
    try {
        Enumeration<Header> allHeaders = getMessage().getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            headerNames.add(allHeaders.nextElement().getName());
        }
        return new ArrayList<>(headerNames);
    } catch (MessagingException ex) {
        throw new SieveMailException(ex);
    }
}
 
Example #9
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private static String formatHeader( Message thisMessage ) throws Exception {
	Enumeration<Header> E	= thisMessage.getAllHeaders();
	StringBuilder	tmp	= new StringBuilder(128);
	while (E.hasMoreElements()){
		Header hdr = E.nextElement();
		tmp.append( hdr.getName() );
		tmp.append( ": " );
		tmp.append( hdr.getValue() );
		tmp.append( "\r\n" );
	}
	
	return tmp.toString();
}
 
Example #10
Source File: ContentIdPredicate.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Part input) {
	try {
		// @formatter:off
		return list(input.getMatchingHeaders(new String[] { "Content-ID" }))
				.stream()
				.map(Header::getValue)
				.anyMatch(contentId::equals);
		// @formatter:on
	} catch (MessagingException e) {
		throw new AssertionError("Failed to access message", e);
	}
}
 
Example #11
Source File: BayesianAnalysisFeeder.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void clearAllHeaders(MimeMessage message) throws javax.mail.MessagingException {
    Enumeration<Header> headers = message.getAllHeaders();

    while (headers.hasMoreElements()) {
        Header header = headers.nextElement();
        try {
            message.removeHeader(header.getName());
        } catch (javax.mail.MessagingException me) {
            LOGGER.error("Cannot remove header.", me);
        }
    }
    message.saveChanges();
}
 
Example #12
Source File: RemoveMimeHeaderByPrefix.java    From james-project with Apache License 2.0 5 votes vote down vote up
private List<String> headerNamesStartingByPrefix(Mail mail) throws MessagingException {
    ImmutableList.Builder<String> headerToRemove = ImmutableList.builder();
    List<Header> headers = new MimeMessageUtils(mail.getMessage()).toHeaderList();
    for (Header header: headers) {
        if (header.getName().startsWith(prefix)) {
            headerToRemove.add(header.getName());
        }
    }
    return headerToRemove.build();
}
 
Example #13
Source File: MimeMessageUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
public List<Header> toHeaderList() throws MessagingException {
    ImmutableList.Builder<Header> headers = ImmutableList.builder();
    Enumeration<Header> allHeaders = message.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
        headers.add(allHeaders.nextElement());
    }
    return headers.build();
}
 
Example #14
Source File: HasHeaderWithPrefix.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    List<Header> headers = new MimeMessageUtils(mail.getMessage()).toHeaderList();

    for (Header header: headers) {
        if (header.getName().startsWith(prefix)) {
            return mail.getRecipients();
        }
    }

    return matchSpecific(mail);
}
 
Example #15
Source File: DKIMSign.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void prependHeader(MimeMessage message, String signatureHeader)
        throws MessagingException {
    List<String> prevHeader = Collections.list(message.getAllHeaderLines());
    Collections.list(message.getAllHeaders())
        .stream()
        .map(Header::getName)
        .forEach(Throwing.consumer(message::removeHeader).sneakyThrow());

    message.addHeaderLine(signatureHeader);
    prevHeader
        .forEach(Throwing.consumer(message::addHeaderLine).sneakyThrow());
}
 
Example #16
Source File: MessageAlteringUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void copyRelevantHeaders(MimeMessage originalMessage, MimeMessage newMessage) throws MessagingException {
    Enumeration<Header> headerEnum = originalMessage.getMatchingHeaders(
            new String[] { RFC2822Headers.DATE, RFC2822Headers.FROM, RFC2822Headers.REPLY_TO, RFC2822Headers.TO, 
                    RFC2822Headers.SUBJECT, RFC2822Headers.RETURN_PATH });
    while (headerEnum.hasMoreElements()) {
        Header header = headerEnum.nextElement();
        newMessage.addHeader(header.getName(), header.getValue());
    }
}
 
Example #17
Source File: JavaMailJMSStatistics.java    From javamail with Apache License 2.0 5 votes vote down vote up
private static CompositeData convert(MessageAndAddresses maa) {
    if (maa == null) {
        return null;
    }
    try {
        TabularData addrData = new TabularDataSupport(TAB_ADDR_TYPE);
        for(Address addr : maa.getAddresses()) {
            addrData.put(new CompositeDataSupport(ROW_ADDR_TYPE, new String[]{"addressType", "address"}, new Object[]{addr.getType(), addr.toString()}));
        }
        TabularData headerData = new TabularDataSupport(TAB_HEADER_TYPE);
        Enumeration en = maa.getMessage().getAllHeaders();
        while (en.hasMoreElements()) {
            Header header = (Header) en.nextElement();
            headerData.put(new CompositeDataSupport(ROW_HEADER_TYPE, new String[]{"header-name", "header-value"}, new Object[]{header.getName(), header.getValue()}));
        }
        String error = null;
        if (maa.getException() != null) {
            StringWriter sw = new StringWriter();
            sw.append(maa.getException().toString());
            maa.getException().printStackTrace(new PrintWriter(sw));
            sw.flush();
            error = sw.toString();
        }
        return new CompositeDataSupport(MAIL_INFO_TYPE,
                new String[] {"messageId", "date", "subject", "toAddresses", "headers", "errorDescription"},
                new Object[]{maa.getMessage().getMessageID(), new Date(maa.getTimestamp()), maa.getMessage().getSubject(), addrData, headerData, error}
        );
    } catch (OpenDataException | MessagingException e) {
        throw new IllegalArgumentException("cannot convert MessageAndAddresses to CompositeData", e);
    }
}
 
Example #18
Source File: TextCalendarBodyToAttachment.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void processTextBodyAsAttachment(MimeMessage mimeMessage) throws MessagingException {
    List<Header> contentHeaders = getContentHeadersFromMimeMessage(mimeMessage);

    removeAllContentHeaderFromMimeMessage(mimeMessage, contentHeaders);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(createMimeBodyPartWithContentHeadersFromMimeMessage(mimeMessage, contentHeaders));

    mimeMessage.setContent(multipart);
    mimeMessage.saveChanges();
}
 
Example #19
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static MimeMessageWrapper wrap(MimeMessage mimeMessage) throws MessagingException {
    try {
        return new MimeMessageWrapper(mimeMessage);
    } catch (MessagingException e) {
        // Copying a mime message fails when the body is empty
        // Copying manually the headers is the best alternative...

        MimeMessageWrapper result = new MimeMessageWrapper();
        ThrowingConsumer<Header> consumer = header -> result.addHeader(header.getName(), header.getValue());
        Collections.list(mimeMessage.getAllHeaders())
            .forEach(Throwing.consumer(consumer).sneakyThrow());
        result.setText(""); // Avoid future body reads to fail
        return result;
    }
}
 
Example #20
Source File: TextCalendarBodyToAttachment.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart createMimeBodyPartWithContentHeadersFromMimeMessage(MimeMessage mimeMessage, List<Header> contentHeaders) throws MessagingException {
    MimeBodyPart fileBody = new MimeBodyPart(mimeMessage.getRawInputStream());
    for (Header header : contentHeaders) {
        fileBody.setHeader(header.getName(), header.getValue());
    }

    fileBody.setDisposition(Part.ATTACHMENT);
    return fileBody;
}
 
Example #21
Source File: MailDto.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static Optional<ImmutableMap<String, HeadersDto>> fetchPerRecipientsHeaders(Set<AdditionalField> additionalFields, Mail mail) {
    if (!additionalFields.contains(AdditionalField.PER_RECIPIENTS_HEADERS)) {
        return Optional.empty();
    }
    Multimap<MailAddress, PerRecipientHeaders.Header> headersByRecipient = mail
            .getPerRecipientSpecificHeaders()
            .getHeadersByRecipient();

    return Optional.of(headersByRecipient
        .keySet()
        .stream()
        .collect(Guavate.toImmutableMap(MailAddress::asString, (address) -> fetchPerRecipientHeader(headersByRecipient, address))));
}
 
Example #22
Source File: MailDto.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static HeadersDto fetchPerRecipientHeader(
        Multimap<MailAddress, PerRecipientHeaders.Header> headersByRecipient,
        MailAddress address) {
    return new HeadersDto(headersByRecipient.get(address)
        .stream()
        .collect(Guavate.toImmutableListMultimap(PerRecipientHeaders.Header::getName, PerRecipientHeaders.Header::getValue)));
}
 
Example #23
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Enumeration<Header> getAllHeaders() throws MessagingException {
    if (headers == null) {
        loadHeaders();
    }
    return headers.getAllHeaders();
}
 
Example #24
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Enumeration<Header> getMatchingHeaders(String[] names) throws MessagingException {
    if (headers == null) {
        loadHeaders();
    }
    return headers.getMatchingHeaders(names);
}
 
Example #25
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Enumeration<Header> getNonMatchingHeaders(String[] names) throws MessagingException {
    if (headers == null) {
        loadHeaders();
    }
    return headers.getNonMatchingHeaders(names);
}
 
Example #26
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String printHeaders(Enumeration<Header> hdrs, String nameValueSeparator, String valuePairSeparator) {
    String headers = "";
    while (hdrs.hasMoreElements()) {
        Header h = hdrs.nextElement();
        headers = headers + valuePairSeparator + h.getName() + nameValueSeparator + h.getValue();
    }

    return (headers);

}
 
Example #27
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static RequestBuilder getRequestBuilder(String method, URL urlObj, NameValuePair[] params, Enumeration<Header> headers) throws URISyntaxException {

        RequestBuilder req = null;
        if (method == null || method.equalsIgnoreCase(Method.GET)) {
            //default get
            req = RequestBuilder.get();
        } else if (method.equalsIgnoreCase(Method.POST)) {
            req = RequestBuilder.post();
        } else if (method.equalsIgnoreCase(Method.HEAD)) {
            req = RequestBuilder.head();
        } else if (method.equalsIgnoreCase(Method.PUT)) {
            req = RequestBuilder.put();
        } else if (method.equalsIgnoreCase(Method.DELETE)) {
            req = RequestBuilder.delete();
        } else if (method.equalsIgnoreCase(Method.TRACE)) {
            req = RequestBuilder.trace();
        } else {
            throw new IllegalArgumentException("Illegal HTTP Method: " + method);
        }
        req.setUri(urlObj.toURI());
        if (params != null && params.length > 0) {
            req.addParameters(params);
        }
        if (headers != null) {
            boolean removeHeaderFolding = "true".equals(Properties.getProperty(HTTP_PROP_REMOVE_HEADER_FOLDING, "true"));
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                String headerValue = header.getValue();
                if (removeHeaderFolding) {
                    headerValue = headerValue.replaceAll("\r\n[ \t]*", " ");
                }
                req.setHeader(header.getName(), headerValue);
            }
        }
        return req;
    }
 
Example #28
Source File: JavaMailJMSStatisticsTest.java    From javamail with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    javaMailJMSStatistics = new JavaMailJMSStatistics();
    javaMailJMSStatistics.registerInJMX();
    mimeMessage = Mockito.mock(MimeMessage.class);
    when(mimeMessage.getAllHeaders()).thenReturn(Collections.enumeration(Arrays.asList(new Header("h1", "v1"), new Header("h2", "v2"))));
    when(mimeMessage.getMessageID()).thenReturn("MessageId");
    when(mimeMessage.getSubject()).thenReturn("MessageSubject");
}
 
Example #29
Source File: BaseMessageMDN.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void copyHeaders(InternetHeaders srcHeaders) {
    Enumeration<Header> headerEn = srcHeaders.getAllHeaders();
    while (headerEn.hasMoreElements()) {
        Header header = headerEn.nextElement();
        setHeader(header.getName(), header.getValue());
    }
}
 
Example #30
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("Message From:").append(getPartnership().getSenderIDs());
    buf.append("To:").append(getPartnership().getReceiverIDs());

    Enumeration<Header> headerEn = getHeaders().getAllHeaders();
    buf.append(System.getProperty("line.separator") + "Headers:{");

    while (headerEn.hasMoreElements()) {
        Header header = headerEn.nextElement();
        buf.append(header.getName()).append("=").append(header.getValue());

        if (headerEn.hasMoreElements()) {
            buf.append(", ");
        }
    }

    buf.append("}");
    buf.append(System.getProperty("line.separator") + "Attributes:").append(getAttributes());

    MessageMDN mdn = getMDN();

    if (mdn != null) {
        buf.append(System.getProperty("line.separator") + "MDN:");
        buf.append(mdn.toString());
    }

    return buf.toString();
}