Example usage for javax.mail Message getHeader

List of usage examples for javax.mail Message getHeader

Introduction

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

Prototype

public String[] getHeader(String header_name) throws MessagingException;

Source Link

Document

Get all the headers for this header name.

Usage

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

@Override
public boolean execute(ExecutionContext context) {
    bodyContent = "";

    boolean copyMessage = Boolean.parseBoolean(Framework.getProperty(COPY_MESSAGE, "false"));

    try {/*from ww w  .  j ava2  s  . c om*/
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage && copyMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        // Subject
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);

        // Sender
        try {
            Address[] from = message.getFrom();
            String sender = null;
            String senderEmail = null;
            if (from != null) {
                Address addr = from[0];
                if (addr instanceof InternetAddress) {
                    InternetAddress iAddr = (InternetAddress) addr;
                    senderEmail = iAddr.getAddress();
                    sender = iAddr.getPersonal() + " <" + senderEmail + ">";
                } else {
                    sender += addr.toString();
                    senderEmail = sender;
                }
            }
            context.put(SENDER_KEY, sender);
            context.put(SENDER_EMAIL_KEY, senderEmail);
        } catch (AddressException ae) {
            // try to parse sender from header instead
            String[] values = message.getHeader("From");
            if (values != null) {
                context.put(SENDER_KEY, values[0]);
            }
        }
        // Sending date
        context.put(SENDING_DATE_KEY, message.getSentDate());

        // Recipients
        try {
            Address[] to = message.getRecipients(Message.RecipientType.TO);
            Collection<String> recipients = new ArrayList<String>();
            if (to != null) {
                for (Address addr : to) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        if (iAddr.getPersonal() != null) {
                            recipients.add(iAddr.getPersonal() + " <" + iAddr.getAddress() + ">");
                        } else {
                            recipients.add(iAddr.getAddress());
                        }
                    } else {
                        recipients.add(addr.toString());
                    }
                }
            }
            context.put(RECIPIENTS_KEY, recipients);
        } catch (AddressException ae) {
            // try to parse recipient from header instead
            Collection<String> recipients = getHeaderValues(message, Message.RecipientType.TO.toString());
            context.put(RECIPIENTS_KEY, recipients);
        }

        // CC recipients

        try {
            Address[] toCC = message.getRecipients(Message.RecipientType.CC);
            Collection<String> ccRecipients = new ArrayList<String>();
            if (toCC != null) {
                for (Address addr : toCC) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        ccRecipients.add(iAddr.getPersonal() + " " + iAddr.getAddress());
                    } else {
                        ccRecipients.add(addr.toString());
                    }
                }
            }
            context.put(CC_RECIPIENTS_KEY, ccRecipients);

        } catch (AddressException ae) {
            // try to parse ccRecipient from header instead
            Collection<String> ccRecipients = getHeaderValues(message, Message.RecipientType.CC.toString());
            context.put(CC_RECIPIENTS_KEY, ccRecipients);
        }
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MailCoreConstants.MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);

        List<Blob> blobs = new ArrayList<Blob>();
        context.put(ATTACHMENTS_KEY, blobs);

        // String[] cte = message.getHeader("Content-Transfer-Encoding");

        // process content
        getAttachmentParts(message, subject, mimeService, context);

        context.put(TEXT_KEY, bodyContent);

        return true;
    } catch (MessagingException | IOException e) {
        log.error(e, e);
    }
    return false;
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

public Collection<String> getHeaderValues(Message message, String headerName) throws MessagingException {
    Collection<String> valuesList = new ArrayList<String>();
    String[] values = message.getHeader(headerName);
    if (values != null) {
        for (String value : values) {
            valuesList.add(value);//from  ww  w .  ja v a  2s. com
        }
    }
    return valuesList;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Retrieve mail for user.//from ww w. j  av a2 s . c  o m
 *
 * @param userType = "P" if logged in user is a provider
 *                   "T" if logged in user is a patient
 * @param userId = unique id of logged in user.
 * @param login = email server user name of logged in user.
 * @param pswd  = password of logged in user.
 * @param folderName = 
 * @param displayName = full name
 * @param onlyNew =
 *
 * @return
 * @throws java.lang.Exception
 */
//private  //DBG ONLY - REMOVE COMMENT MARKS
public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login,
        String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl)
        throws Exception, DatatypeConfigurationException {
    List<SummaryData> dataList = new LinkedList<SummaryData>();
    IMAPSSLStore sslStore = null;
    IMAPFolder currentFolder = null;
    String folderToOpen = folderName;

    System.out.println("===> retrieveMail Incoming params:");
    System.out.println("===>     mailHost=" + mailHost);
    System.out.println("===>      mailUrl=" + mailUrl);
    System.out.println("===>    maillogin=" + login);
    System.out.println("===>   folderName=" + folderName);
    try {
        //Get session
        Session session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);
        //Get the sslStore
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(mailHost, login, pswd);

        folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host);

        currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen);
        currentFolder.open(Folder.READ_ONLY);

        Message[] allMessages = currentFolder.getMessages();

        GregorianCalendar cal = new GregorianCalendar();

        System.out.println("====> FILTER PARAMS for Emails:");
        System.out.println("====>     folder = " + folderToOpen);
        System.out.println("====>     User   = " + login);
        //            System.out.println("====>     from   = "+ patientName +"/"+ patientEmail);
        //            System.out.println("====>     ptid   = "+ patientId);
        System.out.println("====> Total Emails found = " + allMessages.length);
        System.out.println();

        // TMN - CHECK SLOW PERFORMANCE ISSUE HERE:

        //Loop through each email and find ONLY the ones required for return.
        for (Message msg : allMessages) {
            if (msg == null) {
                continue;
            }

            // Keep this in case we want to search entire message
            //
            //                OutputStream os = new ByteArrayOutputStream();
            //                msg.writeTo(os);
            //                String msgContent = os.toString();

            SummaryData summaryData = new SummaryData();
            summaryData.setDataSource(DATA_SOURCE);

            String from = "";
            Address[] fromAddr = msg.getFrom();

            if (fromAddr != null && fromAddr.length > 0) {

                String fromFull = fromAddr[0].toString();
                from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull));

                //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from);

            }

            //------------------------------------------------------
            //FILTERING: Check to exclude email if
            //     0) patientId is passed in as a param
            // AND 1) email does NOT contain PATIENTID=<patientId>
            // AND 2) email FROM field <> patientName
            // AND 3) email FROM field <> patientEmail.
            //
            // because must becoming from EMR inbox and looking for emails
            // addressed to userId BUT only ABOUT or FROM patientId.
            //------------------------------------------------------

            summaryData.setFrom(from);
            summaryData.setAuthor(summaryData.getFrom());
            cal.setTime(msg.getReceivedDate());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

            summaryData.setDescription(msg.getSubject());

            summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName()
                    + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]);

            //this.printMsgIdSubject(msg); //DBG printout

            boolean msgRead = msg.isSet(Flags.Flag.SEEN);
            addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead));

            boolean msgStar = msg.isSet(Flags.Flag.FLAGGED);
            if (msgStar) {
                addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred");
            }

            addNameValue(summaryData.getItemValues(), ITEM_REPLIED,
                    String.valueOf(msg.isSet(Flags.Flag.ANSWERED)));
            addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName());
            if (onlyNew) {
                if (!msg.isSet(Flags.Flag.SEEN)) {
                    dataList.add(summaryData);
                }
            } else {
                dataList.add(summaryData);
            }
        }

    } catch (MessagingException me) {
        log.error("Error in processing email");
        me.printStackTrace();
    } finally {
        // Close connections

        if (currentFolder != null) {
            try {
                currentFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return dataList;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * //from   ww w . ja v  a  2 s. c o  m
 * @param msg
 * @throws MessagingException
 */
void printMsgIdSubject(Message msg) throws MessagingException {
    if ((msg.getHeader("Subject") != null) && (msg.getHeader("Subject").length > 0))

        System.out.println("===> Msg Found: Message-ID=" + msg.getHeader("Message-ID")[0] + " Subject="
                + msg.getHeader("Subject")[0]);
    else
        System.out.println("===> Msg Found: Message-ID=" + msg.getHeader("Message-ID")[0]);
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * @param folder/*from w  ww.j a v  a  2  s .  c  o  m*/
 * @param message
 * @throws MessagingException
 */
public void write(String folder, Message message) throws MessagingException {
    // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder);

    final Store store = getJavamailStore(true);
    store.connect();
    final Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    if (!mailFolder.exists()) {
        mailFolder.create(Folder.HOLDS_MESSAGES);
    }
    mailFolder.open(Folder.READ_WRITE);
    // If message is already archived, do nothing
    final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]);
    if (existingMessage == null) {
        // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only
        // So we clone the message before storing it
        final MimeMessage cloned = cloneEmail(message);
        mailFolder.appendMessages(new Message[] { cloned });
    }

    mailFolder.close(true);
    store.close();
}