Example usage for javax.mail.internet MimeMessage getFrom

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

Introduction

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

Prototype

@Override
public Address[] getFrom() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "From" header fields.

Usage

From source file:de.thm.arsnova.services.UserService.java

private void sendEmail(DbUser dbUser, String subject, String body) {
    MimeMessage msg = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
    try {/*from   ww w .  jav a  2  s  . com*/
        helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">");
        helper.setTo(dbUser.getUsername());
        helper.setSubject(subject);
        helper.setText(body);

        LOGGER.info("Sending mail \"{}\" from \"{}\" to \"{}\"",
                new Object[] { subject, msg.getFrom(), dbUser.getUsername() });
        mailSender.send(msg);
    } catch (MessagingException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    } catch (MailException e) {
        LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e);
    }
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

@Test
public void testExplicitFromAddress() throws Exception {
    EmailInfo myInfo;//from   w ww  .ja va  2 s . co m
    MimeMessage msg;

    // synchronous
    myInfo = new EmailInfo("test@example.com", "Test Email", "Test Body");
    myInfo.setFrom("explicit@example.com");
    emailer.sendEmail(myInfo);
    msg = testMailSender.fetchSentEmail();
    assertEquals("explicit@example.com", msg.getFrom()[0].toString());

    // asynchronous
    myInfo = new EmailInfo("test@example.com", "Test Email", "Test Body");
    myInfo.setFrom("explicit2@example.com");
    emailer.sendEmailAsync(myInfo);

    emailer.processQueuedEmails();
    msg = testMailSender.fetchSentEmail();
    assertEquals("explicit2@example.com", msg.getFrom()[0].toString());
}

From source file:cherry.foundation.mail.MailSendHandlerImplTest.java

@Test
public void testSendNowAttached() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    MailSendHandler handler = create(now);

    ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class);
    doNothing().when(mailSender).send(preparator.capture());

    final File file = File.createTempFile("test_", ".txt", new File("."));
    file.deleteOnExit();/*  w  w w  .  ja va 2 s .  c o m*/
    try {

        try (OutputStream out = new FileOutputStream(file)) {
            out.write("attach2".getBytes());
        }

        final DataSource dataSource = new DataSource() {
            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getName() {
                return "name3.txt";
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream("attach3".getBytes());
            }

            @Override
            public String getContentType() {
                return "text/plain";
            }
        };

        long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"),
                asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() {
                    @Override
                    public void prepare(Attachment attachment) throws MessagingException {
                        attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes()));
                        attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()),
                                "application/octet-stream");
                        attachment.add("name2.txt", file);
                        attachment.add("name3.txt", dataSource);
                    }
                });

        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);
        preparator.getValue().prepare(message);

        assertEquals(0L, messageId);
        assertEquals(1, message.getRecipients(RecipientType.TO).length);
        assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]);
        assertEquals(1, message.getRecipients(RecipientType.CC).length);
        assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]);
        assertEquals(1, message.getRecipients(RecipientType.BCC).length);
        assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]);
        assertEquals(1, message.getFrom().length);
        assertEquals(parse("from@addr")[0], message.getFrom()[0]);
        assertEquals("subject", message.getSubject());

        MimeMultipart mm = (MimeMultipart) message.getContent();
        assertEquals(5, mm.getCount());
        assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent());

        assertEquals("name0.txt", mm.getBodyPart(1).getFileName());
        assertEquals("text/plain", mm.getBodyPart(1).getContentType());
        assertEquals("attach0", mm.getBodyPart(1).getContent());

        assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName());
        assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType());
        assertEquals("attach1", new String(
                ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent())));

        assertEquals("name2.txt", mm.getBodyPart(3).getFileName());
        assertEquals("text/plain", mm.getBodyPart(3).getContentType());
        assertEquals("attach2", mm.getBodyPart(3).getContent());

        assertEquals("name3.txt", mm.getBodyPart(4).getFileName());
        assertEquals("text/plain", mm.getBodyPart(4).getContentType());
        assertEquals("attach3", mm.getBodyPart(4).getContent());
    } finally {
        file.delete();
    }
}

From source file:de.thm.arsnova.service.UserServiceImpl.java

private void sendEmail(UserProfile userProfile, String subject, String body) {
    MimeMessage msg = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8");
    try {//from ww  w . j  a  v  a  2s  .c o  m
        helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">");
        helper.setTo(userProfile.getLoginId());
        helper.setSubject(subject);
        helper.setText(body);

        logger.info("Sending mail \"{}\" from \"{}\" to \"{}\"", subject, msg.getFrom(),
                userProfile.getLoginId());
        mailSender.send(msg);
    } catch (MailException | MessagingException e) {
        logger.warn("Mail \"{}\" could not be sent.", subject, e);
    }
}

From source file:org.jasig.portal.portlets.account.UserAccountHelper.java

public void sendLoginToken(HttpServletRequest request, ILocalAccountPerson account) {

    IPerson person = personManager.getPerson(request);
    final Locale[] userLocales = localeStore.getUserLocales(person);
    LocaleManager localeManager = new LocaleManager(person, userLocales);
    Locale locale = localeManager.getLocales()[0];

    IPortalUrlBuilder builder = urlProvider.getPortalUrlBuilderByPortletFName(request, "reset-password",
            UrlType.RENDER);//from   ww  w  .ja va2  s  . com
    IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder();
    portletUrlBuilder.addParameter("username", account.getName());
    portletUrlBuilder.addParameter("loginToken", (String) account.getAttributeValue("loginToken"));
    portletUrlBuilder.setPortletMode(PortletMode.VIEW);
    portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);

    StringBuffer url = new StringBuffer();
    url.append(request.getScheme());
    url.append("://").append(request.getServerName());
    int port = request.getServerPort();
    if (port != 80 && port != 443) {
        url.append(":").append(port);
    }
    url.append(builder.getUrlString());

    log.debug("Sending password reset instructions to user with url " + url.toString());

    String emailAddress = (String) account.getAttributeValue("mail");

    final STGroup group = new STGroupDir(templateDir, '$', '$');
    final ST template = group.getInstanceOf(passwordResetTemplate);
    template.add("displayName", person.getAttribute("displayName"));
    template.add("url", url.toString());

    MimeMessage message = mailSender.createMimeMessage();
    String body = template.render();

    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(emailAddress);
        helper.setText(body, true);
        helper.setSubject(messageSource.getMessage("reset.your.password", new Object[] {}, locale));
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to " + emailAddress + " from " + Arrays.toString(message.getFrom())
                + " subject " + message.getSubject());
        this.mailSender.send(message);

    } catch (MailException e) {
        log.error("Unable to send password reset email ", e);
    } catch (MessagingException e) {
        log.error("Unable to send password reset email ", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send password reset email ", e);
    }
}

From source file:edu.stanford.muse.util.EmailUtils.java

/**
 * best effort to toString something about the given message.
 * use only for diagnostics, not for user-visible messages.
 * treads defensively, this can be called to report on a badly formatted message.
 *//*from  w w  w  .ja  v a 2 s.  c  o  m*/
public static String formatMessageHeader(MimeMessage m) throws MessagingException {
    StringBuilder sb = new StringBuilder();
    sb.append("To: ");
    if (m == null) {
        log.warn("Trying to format null message!?");
        return "Null message";
    }
    try {
        Address[] tos = m.getAllRecipients();
        if (tos != null)
            for (Address a : tos)
                sb.append(a.toString() + " ");
        sb.append("\n");
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    sb.append("From: ");
    try {
        Address[] froms = m.getFrom();
        if (froms != null)
            for (Address a : froms)
                sb.append(a.toString() + " ");
        sb.append("\n");
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    try {
        sb.append("Subject: " + m.getSubject());
        sb.append("Message-ID: " + m.getMessageID());
    } catch (Exception e) {
        Util.print_exception(e, log);
    }

    return sb.toString();
}

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

public static String getFromDelegate(MimeMessage msg) throws MessagingException {
    String from = null;// ww w  . j  av a  2s  .  c  om
    try {
        from = ALMailUtils.getAddressString(msg.getFrom());
    } catch (AddressException e) {
        logger.info("ALMailUtils.getFromDelegate", e);
        from = ALMailUtils.getFromInetAddressForBroken(msg);
    }
    return from;
}

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

public static String getFromDelegateExtract(MimeMessage msg) throws MessagingException {
    String from = null;//www . ja  v  a  2  s  . c  o  m
    try {
        from = ALMailUtils.getAddressString(msg.getFrom());
    } catch (AddressException e) {
        logger.info("ALMailUtils.getFromDelegateExtract", e);
        from = ALMailUtils.getFromInetAddressForBroken(msg);
        from = ALMailUtils.extractAddress(from);
    }
    return from;
}

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

public static Address[] getFromDelegateExtractForAddress(MimeMessage msg) throws MessagingException {
    Address[] addresses = new InternetAddress[1];
    try {/*w  w w .j a v a2s  . co m*/
        addresses = msg.getFrom();
    } catch (AddressException e) {
        logger.info("ALMailUtils.getFromDelegateExtractForAddress", e);
        String from = ALMailUtils.getFromInetAddressForBroken(msg);
        from = ALMailUtils.extractAddress(from);
        Address address = new InternetAddress(from, false);
        addresses[0] = address;
    }
    return addresses;
}

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

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {/* www . j av  a 2  s . com*/
    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;
}