Example usage for javax.mail.internet MimeMessage getHeader

List of usage examples for javax.mail.internet MimeMessage getHeader

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getHeader.

Prototype

@Override
public String[] getHeader(String name) throws MessagingException 

Source Link

Document

Get all the headers for this header_name.

Usage

From source file:Main.java

public static boolean isReplySign(MimeMessage msg) throws MessagingException {
    boolean replySign = false;
    String[] headers = msg.getHeader("Disposition-Notification-To");
    if (headers != null)
        replySign = true;/*from   w w w  . ja  v  a2 s  .co m*/
    return replySign;
}

From source file:Main.java

private static boolean isReplySign(MimeMessage msg) {
    boolean replySign = false;
    try {/*from   w  w  w .jav a2s  .co  m*/
        String[] header = msg.getHeader("Disposition-Notification-To");
        if (header != null) {
            replySign = true;
        }
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
        return replySign;
    }
}

From source file:MSMessage.java

/**
 * Check whether the given MimeMessage object represents a
 * non-MIME message sent by Outlook.  Such a message will
 * have no MIME-Version header, may have an X-Mailer header
 * that includes the word "Microsoft", and will have at least
 * one X-MS-Attachment header./*from  w  ww  .ja v  a 2 s  .  com*/
 */
public static boolean isMSMessage(MimeMessage msg) throws MessagingException {
    // Check whether the MIME header is present
    if (msg.getHeader("MIME-Version") != null)
        // MIME-Version header present, should be a MIME message
        return false;

    /*
     * XXX - disabled X-Mailer check because many sample messages
     * I saw didn't have an X-Mailer header at all.
     */
    if (false) {
        // Check X-Mailer
        String mailer = msg.getHeader("X-mailer", null);
        if (mailer == null) // No X-mailer ? 
            return false; // Oh well !
        if (mailer.indexOf("Microsoft") == -1) // Not MS stuff ?
            return false;
    }

    // Check X-MS-Attachment header
    // XXX - not all such messages have this header
    String[] att = msg.getHeader("X-MS-Attachment");
    if (att == null || att.length == 0)
        return false;

    return true;
}

From source file:com.buzzdavidson.spork.util.OWAUtils.java

public static String getSingleHeader(MimeMessage message, String header) {
    String retval = "";
    String[] headers = null;//from w ww . ja  v  a  2  s.co  m
    try {
        headers = message.getHeader(header);
    } catch (MessagingException ex) {
        logger.warn("Got exception attempting to fetch header [" + header + "]");
    }
    if (headers != null && headers.length > 0) {
        retval = headers[0];
    }
    return retval;
}

From source file:immf.SendMailBridge.java

private static List<InternetAddress> getRecipients(MimeMessage msg, String type) throws MessagingException {
    List<InternetAddress> r = new ArrayList<InternetAddress>();
    String[] headers = msg.getHeader(type);
    if (headers == null) {
        return r;
    }//  w  w w.ja v  a 2 s  .  c  om
    for (String h : headers) {
        InternetAddress[] addrs = InternetAddress.parse(h);
        CollectionUtils.addAll(r, addrs);
    }
    return r;
}

From source file:com.buzzdavidson.spork.util.OWAUtils.java

public static void populateMetadata(MimeMessage message, Node props) {
    Long length = null;/*from   w  w  w  .j  av a  2s  . com*/
    String lengthStr = fetchText(props, OWAConstants.OWA_FILTER_CONTENT_LENGTH, false);
    if (lengthStr != null) {
        try {
            length = Long.parseLong(lengthStr);
            logger.info("Got content length: " + length);
        } catch (NumberFormatException ex) {
            // do nothing
        }
    }
    //This appears to be the exchange specific message id,
    //looks like      "AQUAAAABXRM/AQAAAAA6N1oAAAAA"
    String idStr = fetchText(props, OWAConstants.OWA_FILTER_ID, false);
    if (idStr != null) {
        try {
            String headerId = "";
            String[] ids = message.getHeader("Message-Id");
            if (ids.length > 0) {
                headerId = ids[0];
            }
            if (headerId.length() > 0) {
                if (!headerId.equals(idStr)) {
                    logger.warn(String.format("******** ID values differ!  header id [%s], message id [%s]",
                            headerId, idStr));
                }
            } else {
                message.setHeader("Message-Id", idStr);
            }
        } catch (MessagingException ex) {
            logger.warn("Unable to handle message id header");
        }
    }
    //TODO: attachment flag? Is this needed at all? owabridge uses it to tweak content-length
    if (length != null) {
        try {
            message.setHeader("Content-Length", length.toString());
        } catch (MessagingException ex) {
            logger.warn("Unable to set content-length header", ex);
        }
    }
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test//from   w w  w. j  a v  a 2 s.  c  o m
public void testMarshal() throws Exception {
    Assert.assertNotNull(testShsMessage);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshal", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    InputStream mimeStream = exchange.getIn().getBody(InputStream.class);

    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream);
    String[] mimeSubject = mimeMessage.getHeader("Subject");
    Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]),
            "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]);

    Assert.assertNull(mimeMessage.getMessageID());

    MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent();
    Assert.assertEquals(multipart.getCount(), 2);

    BodyPart bodyPart = multipart.getBodyPart(1);
    String content = (String) bodyPart.getContent();
    Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY);

    String contentType = bodyPart.getContentType();
    Assert.assertTrue(
            StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE),
            "Content type error");

    String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding");
    Assert.assertNotNull(encodings);
    Assert.assertEquals(encodings.length, 1);
    Assert.assertEquals(encodings[0].toUpperCase(),
            ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase());

    mimeMessage.writeTo(System.out);
}

From source file:davmail.smtp.TestSmtp.java

public void sendAndCheckMessage(MimeMessage mimeMessage, String from, String bcc)
        throws IOException, MessagingException, InterruptedException {
    // generate message id
    mimeMessage.saveChanges();/*  w w w . ja va2 s.  c o m*/
    // mimeMessage.writeTo(System.out);

    // copy Message-id to references header
    mimeMessage.addHeader("references", mimeMessage.getHeader("message-id")[0]);
    if (from != null) {
        writeLine("MAIL FROM:" + from);
    } else {
        writeLine("MAIL FROM:" + session.getEmail());
    }
    readLine();
    if (bcc != null) {
        writeLine("RCPT TO:" + bcc);
        readLine();
    }
    writeLine("RCPT TO:" + Settings.getProperty("davmail.to"));
    readLine();
    writeLine("DATA");
    assertEquals("354 Start mail input; end with <CRLF>.<CRLF>", readLine());
    mimeMessage.writeTo(new DoubleDotOutputStream(socketOutputStream));
    writeLine("");
    writeLine(".");
    assertEquals("250 Queued mail for delivery", readLine());
    // wait for asynchronous message send
    ExchangeSession.MessageList messages = null;
    for (int i = 0; i < 5; i++) {
        messages = session.searchMessages("Sent",
                session.headerIsEqualTo("references", mimeMessage.getMessageID()));
        if (messages.size() > 0) {
            break;
        }
        Thread.sleep(1000);
    }
    assertEquals(1, messages.size());
    ExchangeSession.Message sentMessage = messages.get(0);
    sentMessage.getMimeMessage().writeTo(System.out);
    assertEquals(mimeMessage.getDataHandler().getContent(),
            sentMessage.getMimeMessage().getDataHandler().getContent());
}

From source file:com.duroty.task.POP3ServiceTask.java

/**
 * DOCUMENT ME!//from  w w w  . j  av a 2  s .c o  m
 *
 * @param user DOCUMENT ME!
 * @param mime DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private boolean isSpam(Users user, MimeMessage mime) {
    boolean control = false;
    double probability = 0.0;

    try {
        BayesianAnalysis bayesianAnalysis = new BayesianAnalysis();
        bayesianAnalysis.init(null);
        bayesianAnalysis.service(user.getUseUsername(), null, mime);

        String[] aux = mime.getHeader(BayesianAnalysis.messageIsSpamProbability);

        if ((aux != null) && (aux.length > 0)) {
            for (int i = 0; i < aux.length; i++) {
                probability = Double.parseDouble(aux[i].trim());

                break;
            }
        }

        Iterator it = user.getMailPreferenceses().iterator();

        MailPreferences mailPreferences = (MailPreferences) it.next();

        if (mailPreferences.getMaprSpamTolerance() == -1) {
            return false;
        }

        double tolerance = ((double) mailPreferences.getMaprSpamTolerance()) / 100;

        if ((probability > 0.0) && (tolerance < 1.0) && (probability >= tolerance)) {
            control = true;
        }

        return control;
    } catch (NamingException e) {
        return false;
    } catch (Exception ex) {
        return false;
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();

        return false;
    } catch (Throwable ex) {
        return false;
    }
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Process an email, extracting attachments and constructing a Message.
 *
 * @param mail the email to be processed.
 * @param mailingList the mailing list it is going to be affected to.
 * @param event the event which will be send at the end of all processing.
 * @throws MessagingException/*w  w w  .j  av a2s.  c  om*/
 * @throws IOException
 */
public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event)
        throws MessagingException, IOException {
    String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress();
    if (!mailingList.checkSender(sender)) {
        return;
    }
    Message message = new Message();
    message.setComponentId(mailingList.getComponentId());
    message.setSender(sender);
    message.setSentDate(mail.getSentDate());
    message.setMessageId(mail.getMessageID());
    String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO);
    if (referenceId == null || referenceId.length == 0) {
        referenceId = mail.getHeader(MAIL_HEADER_REFERENCES);
    }
    if (referenceId == null || referenceId.length == 0) {
        message.setReferenceId(null);
    } else {
        message.setReferenceId(referenceId[0]);
    }
    message.setTitle(mail.getSubject());
    SilverTrace.info("mailingList", "MailProcessor.prepareMessage()", "mailinglist.notification.error",
            "Processing message " + mail.getSubject());
    Object content = mail.getContent();
    if (content instanceof Multipart) {
        processMultipart((Multipart) content, message);
    } else if (content instanceof String) {
        processBody((String) content, mail.getContentType(), message);
    }
    event.addMessage(message);
}