Example usage for javax.mail.internet MimeMessage getReplyTo

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

Introduction

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

Prototype

@Override
public Address[] getReplyTo() throws MessagingException 

Source Link

Document

Return the value of the RFC 822 "Reply-To" header field.

Usage

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithStartDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*from  w w  w  . jav  a 2 s.c o m*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithEndDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*from w ww. j  ava  2 s.c om*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);

    responseHandler.waitTillDone(5000);

    assertEquals(1, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:org.drools.task.service.IcalBaseTest.java

public void testSendWithStartandEndDeadline() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, createdBy = users['tony'], activationTime = now}), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) {potentialOwners = [users['steve' ], users['tony' ]]}), ";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')],";
    str += "subjects = [ new I18NText( 'en-UK', 'This is my task subject')],";
    str += "descriptions = [ new I18NText( 'en-UK', 'This is my task description')],";
    str += "deadlines = (with (new Deadlines() ) {";
    str += "    startDeadlines = [ ";
    str += "       (with (new Deadline()) {";
    str += "           date = now";
    str += "       } ) ],";
    str += "    endDeadlines = [";
    str += "        (with (new Deadline()) {";
    str += "             date = new Date( now.time + ( 1000 * 60 * 60 * 24 ) )"; // set to tomorrow
    str += "        } ) ]";
    str += "} ) })";

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), "tony@domain.com");
    userInfo.getEmails().put(users.get("steve"), "steve@domain.com");

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("steve"), "en-UK");
    taskService.setUserinfo(userInfo);/*from  w  w w  .j  a v a2s.  c  o m*/

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null, addTaskResponseHandler);

    long taskId = addTaskResponseHandler.getTaskId();

    BlockingTaskOperationResponseHandler responseHandler = new BlockingTaskOperationResponseHandler();
    client.claim(taskId, users.get("steve").getId(), responseHandler);
    responseHandler.waitTillDone(5000);

    assertEquals(2, getWiser().getMessages().size());

    assertEquals("steve@domain.com", getWiser().getMessages().get(0).getEnvelopeReceiver());
    assertEquals("steve@domain.com", getWiser().getMessages().get(1).getEnvelopeReceiver());

    String subject = "Summary\n-------\n\nThis is my task subject\n\n";
    String description = "Description\n-----------\n\nThis is my task description";

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment Start Event: This is my task name", msg.getSubject());

    MimeMultipart multiPart = (MimeMultipart) msg.getContent();

    BodyPart messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    String content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-Start-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task Start : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));

    msg = ((WiserMessage) getWiser().getMessages().get(1)).getMimeMessage();
    assertEqualsIgnoreWhitespace("multipart/alternative;boundary=\"----=_Part_", msg.getContentType(), 0, 47);
    assertEquals("tony@domain.com", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("tony@domain.com", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    assertEquals("steve@domain.com", ((InternetAddress) msg.getRecipients(RecipientType.TO)[0]).getAddress());
    assertEquals("Task Assignment End Event: This is my task name", msg.getSubject());

    multiPart = (MimeMultipart) msg.getContent();

    messageBodyPart = multiPart.getBodyPart(0);
    assertEquals("text/plain; charset=UTF8;", messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(subject + description, content);

    messageBodyPart = multiPart.getBodyPart(1);
    assertEquals("text/calendar; charset=UTF8; name=ical-End-1.ics",
            messageBodyPart.getDataHandler().getContentType());
    content = new String(getBytes(messageBodyPart.getDataHandler().getInputStream()));
    assertEqualsIgnoreWhitespace(
            "BEGIN:VCALENDARPRODID:-//iCal4j 1.0//ENCALSCALE:GREGORIANVERSION:2.0METHOD:REQUESTBEGIN:VEVENTDTSTART;TZID=UTC:",
            content.substring(0, 123));
    assertEqualsIgnoreWhitespace(
            "SUMMARY:\"Task End : This is my task subject\"DESCRIPTION:\"This is my task description\"PRIORITY:55END:VEVENTEND:VCALENDAR",
            content.substring(content.length() - 131, content.length()));
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

public static Address getReplyToDelegateExtract(MimeMessage msg) throws MessagingException {
    Address replyTo = null;/*www .  ja  va2 s  . c  om*/
    try {
        replyTo = msg.getReplyTo()[0];
    } catch (AddressException e) {
        logger.info("ALMailUtils.getReplyToDelegateExtract", e);
        String _replyTo = getReplytoInetAddressForBroken(msg);
        _replyTo = ALMailUtils.extractAddress(_replyTo);
        replyTo = new InternetAddress(_replyTo, false);
    }
    return replyTo;
}

From source file:org.apache.axis2.transport.mail.server.MailSorter.java

public void processMail(ConfigurationContext confContext, MimeMessage mimeMessage) {
    // create an Axis server
    AxisEngine engine = new AxisEngine(confContext);
    MessageContext msgContext = null;

    // create and initialize a message context
    try {/*  w ww . j  a v a2 s  . c o  m*/
        msgContext = confContext.createMessageContext();
        msgContext.setTransportIn(
                confContext.getAxisConfiguration().getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL));
        msgContext.setTransportOut(
                confContext.getAxisConfiguration().getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL));

        msgContext.setServerSide(true);
        msgContext.setProperty(Constants.CONTENT_TYPE, mimeMessage.getContentType());
        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                mimeMessage.getEncoding());
        String soapAction = getMailHeader(Constants.HEADER_SOAP_ACTION, mimeMessage);
        if (soapAction == null) {
            soapAction = mimeMessage.getSubject();
        }

        msgContext.setSoapAction(soapAction);
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        String serviceURL = mimeMessage.getSubject();

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

        String replyTo = ((InternetAddress) mimeMessage.getReplyTo()[0]).getAddress();

        if (replyTo != null) {
            msgContext.setReplyTo(new EndpointReference(replyTo));
        }

        String recepainets = ((InternetAddress) mimeMessage.getAllRecipients()[0]).getAddress();

        if (recepainets != null) {
            msgContext.setTo(new EndpointReference(recepainets + "/" + serviceURL));
        }

        // add the SOAPEnvelope
        String message = mimeMessage.getContent().toString();

        log.info("message[" + message + "]");

        ByteArrayInputStream bais = new ByteArrayInputStream(message.getBytes());
        String soapNamespaceURI = "";

        if (mimeMessage.getContentType().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        } else if (mimeMessage.getContentType().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        }

        StAXBuilder builder = BuilderUtil.getSOAPBuilder(bais, soapNamespaceURI);

        SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement();

        msgContext.setEnvelope(envelope);

        AxisEngine.receive(msgContext);
    } catch (Exception e) {
        try {
            if (msgContext != null) {
                MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e);

                engine.sendFault(faultContext);
            }
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

private void assertMailSent(MailToSend verifiedMailToSend) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));/*w w  w .j  a v  a  2 s  . co  m*/

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = greenMailRule.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));//from  w  ww .j a  v  a 2s.  com

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = mail.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * fix up From and ReplyTo if we need it to be from Postmaster
 *///from   ww  w. jav  a 2 s .  co m
private void checkFrom(MimeMessage msg) {

    String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true");
    String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null);
    InternetAddress from = null;
    InternetAddress[] replyTo = null;

    try {
        Address[] fromA = msg.getFrom();
        if (fromA == null || fromA.length == 0) {
            M_log.info("message from missing");
            return;
        } else if (fromA.length > 1) {
            M_log.info("message from more than 1");
            return;
        } else if (fromA instanceof InternetAddress[]) {
            from = (InternetAddress) fromA[0];
        } else {
            M_log.info("message from not InternetAddress");
            return;
        }

        Address[] replyToA = msg.getReplyTo();
        if (replyToA == null)
            replyTo = null;
        else if (replyToA instanceof InternetAddress[])
            replyTo = (InternetAddress[]) replyToA;
        else {
            M_log.info("message replyto isn't internet address");
            return;
        }

        // should we replace from address with a Sakai address?
        if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) {
            // exceptions -- addresses to leave alone. Our own addresses are always exceptions.
            // you can also configure a regexp of exceptions.
            if (!from.getAddress().toLowerCase()
                    .endsWith("@" + serverConfigurationService.getServerName().toLowerCase())
                    && (sendExceptions == null || sendExceptions.equals("")
                            || !from.getAddress().toLowerCase().matches(sendExceptions))) {

                // not an exception. do the replacement.
                // First, decide on the replacement address. The config variable
                // may be the replacement address. If not, use postmaster
                if (sendFromSakai.indexOf("@") < 0)
                    sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName();

                // put the original from into reply-to, unless a replyto exists
                if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) {
                    replyTo = new InternetAddress[1];
                    replyTo[0] = from;
                    msg.setReplyTo(replyTo);
                }
                // for some reason setReplyTo doesn't work, though setFrom does. Have to create the
                // actual header line
                if (msg.getHeader(EmailHeaders.REPLY_TO) == null)
                    msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress());

                // and use the new from address
                // biggest issue is the "personal address", i.e. the comment text

                String origFromText = from.getPersonal();
                String origFromAddress = from.getAddress();
                String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT,
                        "{}");

                String fromText = null;
                if (origFromText != null && !origFromText.equals(""))
                    fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")");
                else
                    fromText = fromTextPattern.replace("{}", origFromAddress);

                from = new InternetAddress(sendFromSakai);
                try {
                    from.setPersonal(fromText);
                } catch (Exception e) {
                }

                msg.setFrom(from);
            }
        }
    } catch (javax.mail.internet.AddressException e) {
        M_log.info("checkfrom address exception " + e);
    } catch (javax.mail.MessagingException e) {
        M_log.info("checkfrom messaging exception " + e);
    }

}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {/* w  w w  .ja v a2 s .c om*/
    File oldDir = argument.currentOutputDir;
    if (argument.currentOutputDir == null) {
        if (config.outputDir != null) {
            argument.currentOutputDir = new File(config.outputDir);
        }
    }
    Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
    Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
    String skey = "";
    String id = config.addRankId(root);
    Address[] from = null;
    Element sub2 = null;
    try {
        from = message.getFrom();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("From");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);
            }
        } catch (MessagingException e) {
        }
    }
    Address sender = null;
    try {
        sender = message.getSender();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Sender");
            if (partialResult != null && partialResult.length > 0) {
                if (sub2 == null) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            }
        } catch (MessagingException e) {
        }
    }
    if (from != null && from.length > 0) {
        String value0 = null;
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        if (sender != null) {
            value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        }
        for (Address address : from) {
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
        }
        metadata.add(sub);
    } else if (sender != null) {
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        metadata.add(sub);
    } else {
        if (sub2 != null) {
            metadata.add(sub2);
        }
    }
    Address[] replyTo = null;
    try {
        replyTo = message.getReplyTo();
        if (replyTo != null && replyTo.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
            for (Address address : replyTo) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("ReplyTo");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] toRecipients = null;
    try {
        toRecipients = message.getRecipients(Message.RecipientType.TO);
        if (toRecipients != null && toRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
            for (Address address : toRecipients) {
                addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("To");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] ccRecipients;
    try {
        ccRecipients = message.getRecipients(Message.RecipientType.CC);
        if (ccRecipients != null && ccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
            for (Address address : ccRecipients) {
                addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] bccRecipients;
    try {
        bccRecipients = message.getRecipients(Message.RecipientType.BCC);
        if (bccRecipients != null && bccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
            for (Address address : bccRecipients) {
                addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    try {
        String subject = message.getSubject();
        if (subject != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
            sub.setText(StringUtils.unescapeHTML(subject, true, false));
            metadata.add(sub);
        }
        Date sentDate = message.getSentDate();
        if (sentDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
            sub.setText(sentDate.toString());
            metadata.add(sub);
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
            sub.setText(receivedDate.toString());
            metadata.add(sub);
        }
        String[] headers = message.getHeader("Received");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
            MailDateFormat mailDateFormat = null;
            long maxTime = 0;
            if (receivedDate == null) {
                mailDateFormat = new MailDateFormat();
            }
            for (String string : headers) {
                Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                sub3.setText(StringUtils.unescapeHTML(string, true, false));
                sub.add(sub3);
                if (receivedDate == null) {
                    int pos = string.lastIndexOf(';');
                    if (pos > 0) {
                        String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                        try {
                            Date date = mailDateFormat.parse(recvdate);
                            if (date.getTime() > maxTime) {
                                maxTime = date.getTime();
                            }
                        } catch (ParseException e) {
                        }
                    }
                }
            }
            if (receivedDate == null) {
                Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                Date date = new Date(maxTime);
                subdate.setText(date.toString());
                metadata.add(subdate);
            }
            metadata.add(sub);
        }
        int internalSize = message.getSize();
        if (internalSize > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
            sub.setText(Integer.toString(internalSize));
            metadata.add(sub);
        }
        String encoding = message.getEncoding();
        if (encoding != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
            sub.setText(StringUtils.unescapeHTML(encoding, true, false));
            metadata.add(sub);
        }
        String description = message.getDescription();
        if (description != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            sub.setText(StringUtils.unescapeHTML(description, true, false));
            metadata.add(sub);
        }
        String contentType = message.getContentType();
        if (contentType != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
            sub.setText(StringUtils.unescapeHTML(contentType, true, false));
            metadata.add(sub);
        }
        headers = message.getHeader("Content-Transfer-Encoding");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String[] contentLanguage = message.getContentLanguage();
        if (contentLanguage != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
            StringBuilder builder = new StringBuilder();
            for (String string : contentLanguage) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String contentId = message.getContentID();
        if (contentId != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
            metadata.add(sub);
        }
        String disposition = message.getDisposition();
        if (disposition != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
            metadata.add(sub);
        }
        headers = message.getHeader("Keywords");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String messageId = message.getMessageID();
        if (messageId != null) {
            messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
            if (messageId.length() > 1) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                sub.setText(messageId);
                metadata.add(sub);
            }
        }
        headers = message.getHeader("In-Reply-To");
        String inreplyto = null;
        if (headers != null) {
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            inreplyto = builder.toString().trim();
            if (inreplyto.length() > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                sub.setText(inreplyto);
                if (messageId != null && messageId.length() > 1) {
                    String old = filEmls.get(inreplyto);
                    if (old == null) {
                        old = messageId;
                    } else {
                        old += "," + messageId;
                    }
                    filEmls.put(inreplyto, old);
                }
                metadata.add(sub);
            }
        }
        headers = message.getHeader("References");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            String[] refs = builder.toString().trim().split(" ");
            for (String string : refs) {
                if (string.length() > 0) {
                    Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                    ref.setText(string);
                    sub.add(ref);
                }
            }
            metadata.add(sub);
        }
        Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
        headers = message.getHeader("X-Priority");
        if (headers == null) {
            headers = message.getHeader("Priority");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
            }
        } else if (headers != null && headers.length > 0) {
            String imp = headers[0];
            try {
                int Priority = Integer.parseInt(imp);
                switch (Priority) {
                case 5:
                    imp = "LOWEST";
                    break;
                case 4:
                    imp = "LOW";
                    break;
                case 3:
                    imp = "NORMAL";
                    break;
                case 2:
                    imp = "HIGH";
                    break;
                case 1:
                    imp = "HIGHEST";
                    break;
                default:
                    imp = "LEV" + Priority;
                }
            } catch (NumberFormatException e) {
                // ignore since imp will be used as returned
            }
            prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
        }
        headers = message.getHeader("Sensitivity");
        if (headers != null && headers.length > 0) {
            prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
        }
        headers = message.getHeader("X-RDF");
        if (headers != null && headers.length > 0) {
            System.err.println("Found X-RDF");
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(string);
                builder.append("\n");
            }
            try {
                byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                String rdf = new String(decoded);
                Document tempDocument = DocumentHelper.parseText(rdf);
                Element xrdf = prop.addElement("x-rdf");
                xrdf.add(tempDocument.getRootElement());
            } catch (Exception e) {
                System.err.println("Cannot decode X-RDF: " + e.getMessage());
            }
        }
        try {
            File old = argument.currentOutputDir;
            if (config.extractFile) {
                File newOutDir = new File(argument.currentOutputDir, id);
                newOutDir.mkdirs();
                argument.currentOutputDir = newOutDir;
            }
            if (argument.extractKeyword) {
                skey = handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
                ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                if (keywords.hasContent()) {
                    root.add(keywords);
                }
            } else {
                handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
            }
            argument.currentOutputDir = old;
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        try {
            message.getInputStream().close();
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        root.addAttribute(EMAIL_FIELDS.status.name, "ok");
    } catch (MessagingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    } catch (Exception e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    argument.currentOutputDir = oldDir;
    return skey;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder.//from   www.  ja  v  a  2 s .  c o m
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}