Java Code Examples for javax.mail.internet.MimeMessage#getAllHeaders()

The following examples show how to use javax.mail.internet.MimeMessage#getAllHeaders() . 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: 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 2
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 3
Source File: ImapServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void persistMessageHeaders(NodeRef messageRef, MimeMessage message)
{
    try
    {
        Enumeration<Header> headers = message.getAllHeaders();
        List<String> messaheHeadersProperties = new ArrayList<String>();
        while(headers.hasMoreElements())
        {
            Header header = headers.nextElement();
            if (isPersistableHeader(header))
            {
                messaheHeadersProperties.add(header.getName() + ImapModel.MESSAGE_HEADER_TO_PERSIST_SPLITTER + header.getValue());
                
                if (logger.isDebugEnabled())
                {
                    logger.debug("[persistHeaders] Persisting Header " + header.getName() + " : " + header.getValue());
                }
            }
        }
        
        Map<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ImapModel.PROP_MESSAGE_HEADERS, (Serializable)messaheHeadersProperties);
        
        serviceRegistry.getNodeService().addAspect(messageRef, ImapModel.ASPECT_IMAP_MESSAGE_HEADERS, props);
    }
    catch(MessagingException me)
    {
        
    }
}
 
Example 4
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 5
Source File: AbstractEmailTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the {@link MimeMessage} from the {@code WiserMessage}
 * passed in. The headers are serialized first followed by the message
 * body.
 *
 * @param wiserMessage The {@code WiserMessage} to serialize.
 * @return The string format of the message.
 * @throws MessagingException
 * @throws IOException
 *             Thrown while serializing the body from
 *             {@link DataHandler#writeTo(java.io.OutputStream)}.
 * @throws MessagingException
 *             Thrown while getting the body content from
 *             {@link MimeMessage#getDataHandler()}
 * @since 1.1
 */
private String serializeEmailMessage(final WiserMessage wiserMessage)
        throws MessagingException, IOException
{
    if (wiserMessage == null)
    {
        return "";
    }

    final StringBuffer serializedEmail = new StringBuffer();
    final MimeMessage message = wiserMessage.getMimeMessage();

    // Serialize the headers
    for (final Enumeration<?> headers = message.getAllHeaders(); headers
            .hasMoreElements();)
    {
        final Header header = (Header) headers.nextElement();
        serializedEmail.append(header.getName());
        serializedEmail.append(": ");
        serializedEmail.append(header.getValue());
        serializedEmail.append(LINE_SEPARATOR);
    }

    // Serialize the body
    final byte[] messageBody = getMessageBodyBytes(message);

    serializedEmail.append(LINE_SEPARATOR);
    serializedEmail.append(messageBody);
    serializedEmail.append(LINE_SEPARATOR);

    return serializedEmail.toString();
}
 
Example 6
Source File: EmailSmtpConnector.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));

        // We must encode our headers ourselves as we have no guarantee that they were in the provided data.
        // This is required to support UTF-8 characters from user display names or room names in the subject header per example
        Enumeration<Header> headers = msg.getAllHeaders();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();
            msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue()));
        }

        msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent));
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");

        if (cfg.getTls() < 3) {
            transport.setStartTLS(cfg.getTls() > 0);
            transport.setRequireStartTLS(cfg.getTls() > 1);
        }

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) {
            log.info("Not using SMTP authentication");
            transport.connect();
        } else {
            log.info("Using SMTP authentication");
            transport.connect(cfg.getLogin(), cfg.getPassword());
        }

        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}
 
Example 7
Source File: MimeReader.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGetNext(final JCas jCas) throws IOException, CollectionException {
  final Path path = files.pop();
  final File file = path.toFile();

  final int left = files.size();

  getMonitor()
      .info(
          "Processing {} ({} %)",
          file.getAbsolutePath(), String.format("%.2f", 100 * (total - left) / (double) total));

  try (FileInputStream is = new FileInputStream(file)) {
    final Session s = Session.getDefaultInstance(new Properties());
    final MimeMessageParser parser = new MimeMessageParser(new MimeMessage(s, is));
    parser.parse();
    final MimeMessage message = parser.getMimeMessage();

    final DocumentAnnotation da = UimaSupport.getDocumentAnnotation(jCas);
    da.setTimestamp(calculateBestDate(message, file));
    da.setDocType("email");
    da.setDocumentClassification("O");
    String source = file.getAbsolutePath().substring(rootFolder.length());
    da.setSourceUri(source);
    da.setLanguage("en");

    // Add all headers as metadata, with email prefix
    final Enumeration<Header> allHeaders = message.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
      final Header header = allHeaders.nextElement();
      addMetadata(jCas, "email." + header.getName(), header.getValue());
    }

    addMetadata(jCas, "from", parser.getFrom());
    addMetadata(jCas, "to", parser.getTo());
    addMetadata(jCas, "cc", parser.getCc());
    addMetadata(jCas, "bcc", parser.getBcc());
    addMetadata(jCas, "subject", parser.getSubject());

    // Add fake title
    addMetadata(jCas, "title", parser.getSubject());

    String actualContent = parser.getPlainContent();

    if (actualContent == null) {
      actualContent = "";
    }

    // TODO: At this point we could create a representation of the addresses, etc in the content
    // eg a table of to, from, and etc
    // then annotate them a commsidentifier, date, person.
    // We could also create relations between sender and receiver

    String content = actualContent + "\n\n---\n\n";

    final String headerBlock = createHeaderBlock(content.length(), jCas, parser);
    content = content + headerBlock;

    final Text text = new Text(jCas);
    text.setBegin(0);
    text.setEnd(actualContent.length());
    text.addToIndexes();

    extractContent(new ByteArrayInputStream(content.getBytes()), source, jCas);
  } catch (final Exception e) {
    getMonitor().warn("Discarding message", e);
  }
}