Example usage for javax.mail Header getValue

List of usage examples for javax.mail Header getValue

Introduction

In this page you can find the example usage for javax.mail Header getValue.

Prototype

public String getValue() 

Source Link

Document

Returns the value of this header.

Usage

From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java

@Override
public Data next() {
    MBoxData mBoxData = null;/*from  w  w w .  j a va  2 s .c o  m*/
    Message message;

    try {
        message = inbox.getMessage(currentMessage);

        if (logger.isDebugEnabled()) {
            logger.debug("Processing message " + currentMessage + " of " + messageCount + "");

            if (logger.isTraceEnabled()) {
                logger.trace("------- MESSAGE START -------");
                logger.trace(message.getContent().toString());
                logger.trace("-------  MESSAGE END  -------");
            }
        }

        mBoxData = new MBoxData(message.getContent().toString());
        mBoxData.setBody(message.getContent().toString());

        StringBuilder stringBuilder = new StringBuilder();
        Enumeration<Header> enumeration = message.getAllHeaders();
        while (enumeration.hasMoreElements()) {
            Header header = enumeration.nextElement();

            if (header.getName().equalsIgnoreCase("from")) {
                mBoxData.setOriginator(header.getValue());
            } else {
                stringBuilder.append(header.getValue());
            }

            if (header.getName().equalsIgnoreCase("date")) {
                String strDate = header.getValue();
                Date date = getDate(strDate);

                mBoxData.setDate(date);
            }

            stringBuilder.append('\n');
        }

        mBoxData.setHeader(stringBuilder.toString());
    } catch (MessagingException e) {
        logger.error("Unable to process message " + currentMessage + ": " + e.getMessage(), e);
    } catch (IOException e) {
        logger.error("I/O error while processing the message " + currentMessage + ": " + e.getMessage(), e);
    }

    currentMessage++;
    return mBoxData;
}

From source file:info.jtrac.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * (and now I guess in many JTrac installations worldwide)
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from   w  ww .  j ava2  s .co  m*/
private void sendInNewThread(final MimeMessage message) {
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed", e);
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.info(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

From source file:com.netspective.commons.message.SendMail.java

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }//  w w w  .  j  a va2  s.co  m
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}

From source file:me.normanmaurer.camel.smtp.SMTPTest.java

@SuppressWarnings("unchecked")
@Test//from  w  w  w.j a va2  s . c om
public void testSendMatchingMessage() throws Exception {
    String sender = "sender@localhost";
    String rcpt = "rcpt@localhost";
    String body = "Subject: test\r\n\r\nTestmail";
    SMTPClient client = new SMTPClient();
    client.connect("localhost", 2525);
    client.helo("localhost");
    client.setSender(sender);
    client.addRecipient(rcpt);

    client.sendShortMessageData(body);
    client.quit();
    client.disconnect();
    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(InputStream.class);
    Exchange ex = resultEndpoint.getReceivedExchanges().get(0);
    Map<String, Object> headers = ex.getIn().getHeaders();
    assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS));
    assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST));

    // check type converter
    MimeMessage message = ex.getIn().getBody(MimeMessage.class);
    Enumeration<Header> mHeaders = message.getAllHeaders();
    Header header = null;
    while (mHeaders.hasMoreElements()) {
        header = mHeaders.nextElement();
        if (header.getName().equals("Subject")) {
            break;
        }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");

    resultEndpoint.assertIsSatisfied();
}

From source file:com.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????// ww w .j a  v a 2s  .  c  o  m
 *
 * @return ?
 * @throws MessagingException
 */
@SuppressWarnings("unchecked")
public Properties getHeaders() throws MessagingException {
    Properties p = new Properties();
    for (Enumeration<Header> headers = message.getAllHeaders(); headers.hasMoreElements();) {
        Header header = headers.nextElement();
        p.setProperty(header.getName(), header.getValue());
    }
    return p;
}

From source file:MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * (and now I guess in many JTrac installations worldwide)
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from   ww  w .  jav  a 2  s  . c o m*/
private void sendInNewThread(final MimeMessage message) {
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");

            // major: nested try catch. It's really ugly.
            // It appears to be caused by getAllHeaders that is throwing
            // a MessagingException.
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed", e);
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.info(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end");
                }
                // major: why propagating a RuntimeException in a thread?
                // It's going to be swallowed in its own thread of execution
                // No one will see it. Also, this is a duplicated catch.
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public MessageHeaderInfo getMessageHeaderInfo() {
    MessageHeaderInfo headerInfo = null;
    try {//from  w  w  w . ja  v  a 2s. c om
        Map<String, String> registry = new HashMap<String, String>();

        // message header tags used to get header information
        String[] headers = new String[] { Constants.MESSAGE_ID, Constants.MESSAGE_SUBJECT,
                Constants.MESSAGE_IN_REPLY_TO, Constants.MESSAGE_REFERENCES };

        @SuppressWarnings("unchecked")
        Enumeration<Header> matchingHeaders = source.getMatchingHeaders(headers);

        while (matchingHeaders.hasMoreElements()) {
            Header header = matchingHeaders.nextElement();
            registry.put(header.getName(), header.getValue());
        }

        if (!registry.isEmpty()) {
            String messageId = registry.get(Constants.MESSAGE_ID);
            String subject = registry.get(Constants.MESSAGE_SUBJECT);
            String inReplyTo = registry.get(Constants.MESSAGE_IN_REPLY_TO);
            String references = registry.get(Constants.MESSAGE_REFERENCES);

            if (messageId != null) {
                headerInfo = new MessageHeaderInfo(messageId);
                headerInfo.setSubject(subject);
                headerInfo.setInReplyTo(inReplyTo);

                if (references != null) {
                    StringTokenizer st = new StringTokenizer(references, "\n");
                    while (st.hasMoreTokens()) {
                        String reference = st.nextToken().trim();
                        headerInfo.addReferences(reference);
                    }
                }
            }
        }
    } catch (final Exception e) {
        throw new GmailException("Failed getting message header information", e);
    }
    return headerInfo;
}

From source file:gr.abiss.calipso.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from w ww.j  a v a2 s. c om*/
private void sendInNewThread(final MimeMessage message) {
    //       try {
    //          logger.info("Sending message: " + message.getSubject() + "\n" + message.getContent());
    //      } catch (MessagingException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("Message contenttype: " + message.getContentType());
            logger.debug("Message content: " + message.getContent());
            Enumeration headers = message.getAllHeaders();

            logger.debug("Message Headers...");
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                logger.error(h.getName() + ": " + h.getValue());
            }
            logger.debug("Message flags: " + message.getFlags());
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed, dumping headers: ");
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.error(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end, exception follows", e);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

From source file:com.stimulus.archiva.domain.Email.java

protected String getIHeaders(boolean journal, boolean showHidden) throws MessagingException, IOException {
    StringBuffer headerOut = new StringBuffer();
    Enumeration headers = null;//from w w  w . j a  v  a  2s . c o  m
    headers = getAllHeaders();

    while (headers.hasMoreElements()) {
        Header header = (Header) headers.nextElement();
        headerOut.append(header.getName());
        headerOut.append(": ");
        headerOut.append(header.getValue());
        headerOut.append("\n");
    }
    return headerOut.toString();
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

private boolean extractMessage(Message Mess, long messageID, String attachURI, String attachDIR) {
    cfArrayData ADD = cfArrayData.createArray(1);

    try {/*from w  ww  . j a  v a 2 s . c om*/

        setData("subject", new cfStringData(Mess.getSubject()));
        setData("id", new cfNumberData(messageID));

        //--- Pull out all the headers
        cfStructData headers = new cfStructData();
        Enumeration<Header> eH = Mess.getAllHeaders();
        String headerKey;
        while (eH.hasMoreElements()) {
            Header hdr = eH.nextElement();

            headerKey = hdr.getName().replace('-', '_').toLowerCase();
            if (headers.containsKey(headerKey)) {
                headers.setData(headerKey,
                        new cfStringData(headers.getData(headerKey).toString() + ";" + hdr.getValue()));
            } else
                headers.setData(headerKey, new cfStringData(hdr.getValue()));
        }

        setData("headers", headers);

        // Get the Date
        Date DD = Mess.getReceivedDate();
        if (DD == null)
            setData("rxddate", new cfDateData(System.currentTimeMillis()));
        else
            setData("rxddate", new cfDateData(DD.getTime()));

        DD = Mess.getSentDate();
        if (DD == null)
            setData("sentdate", new cfDateData(System.currentTimeMillis()));
        else
            setData("sentdate", new cfDateData(DD.getTime()));

        // Get the FROM field
        Address[] from = Mess.getFrom();
        if (from != null && from.length > 0) {
            cfStructData sdFrom = new cfStructData();
            String name = ((InternetAddress) from[0]).getPersonal();
            if (name != null)
                sdFrom.setData("name", new cfStringData(name));

            sdFrom.setData("email", new cfStringData(((InternetAddress) from[0]).getAddress()));
            setData("from", sdFrom);
        }

        //--[ Get the TO/CC/BCC field
        cfArrayData AD = extractAddresses(Mess.getRecipients(Message.RecipientType.TO));
        if (AD != null)
            setData("to", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.CC));
        if (AD != null)
            setData("cc", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.BCC));
        if (AD != null)
            setData("bcc", AD);

        AD = extractAddresses(Mess.getReplyTo());
        if (AD != null)
            setData("replyto", AD);

        //--[ Set the flags
        setData("answered", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.ANSWERED)));
        setData("deleted", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DELETED)));
        setData("draft", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DRAFT)));
        setData("flagged", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.FLAGGED)));
        setData("recent", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.RECENT)));
        setData("seen", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.SEEN)));

        setData("size", new cfNumberData(Mess.getSize()));
        setData("lines", new cfNumberData(Mess.getLineCount()));

        String tmp = Mess.getContentType();
        if (tmp.indexOf(";") != -1)
            tmp = tmp.substring(0, tmp.indexOf(";"));

        setData("mimetype", new cfStringData(tmp));

        // Get the body of the email
        extractBody(Mess, ADD, attachURI, attachDIR);

    } catch (Exception E) {
        return false;
    }

    setData("body", ADD);
    return true;
}