Example usage for javax.mail Message getReplyTo

List of usage examples for javax.mail Message getReplyTo

Introduction

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

Prototype

public Address[] getReplyTo() throws MessagingException 

Source Link

Document

Get the addresses to which replies should be directed.

Usage

From source file:msgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;//from ww  w. j av  a2 s  .c om
    // FROM 
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("FROM: " + a[j].toString());
    }

    // REPLY TO
    if ((a = m.getReplyTo()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("REPLY TO: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) {
            pr("TO: " + a[j].toString());
            InternetAddress ia = (InternetAddress) a[j];
            if (ia.isGroup()) {
                InternetAddress[] aa = ia.getGroup(false);
                for (int k = 0; k < aa.length; k++)
                    pr("  GROUP: " + aa[k].toString());
            }
        }
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            continue; // skip it
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        pr("X-Mailer: " + hdrs[0]);
    else
        pr("X-Mailer NOT available");
}

From source file:com.canoo.webtest.plugins.emailtest.AbstractSelectStep.java

boolean messageMatches(final Message message) throws MessagingException {
    if (!doMatch(getFrom(), message.getFrom()[0].toString())) {
        return false;
    }//from   w  ww.  ja va  2s .  co  m
    if (!doMatch(getSubject(), message.getSubject())) {
        return false;
    }
    if (!doMatchMultiple(getReplyTo(), message.getReplyTo())) {
        return false;
    }
    if (!doMatchMultiple(getCc(), message.getRecipients(MimeMessage.RecipientType.CC))) {
        return false;
    }
    return doMatchMultiple(getTo(), message.getRecipients(MimeMessage.RecipientType.TO));
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument,
        Folder folder, Message message, String id) throws Exception {

    crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id);
    crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(),
            Integer.toString(message.getMessageNumber()));
    if (message instanceof MimeMessage)
        crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(),
                ((MimeMessage) message).getContentID());
    crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject());
    putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(),
            MailboxFieldEnum.from_personal.name());
    putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(),
            MailboxFieldEnum.reply_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO),
            MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC),
            MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC),
            MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name());
    Date dt = message.getSentDate();
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString());
    dt = message.getReceivedDate();//  w ww . jav a2 s .c  o  m
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString());
    if (message.isSet(Flag.ANSWERED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED");
    if (message.isSet(Flag.DELETED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED");
    if (message.isSet(Flag.DRAFT))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT");
    if (message.isSet(Flag.FLAGGED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED");
    if (message.isSet(Flag.SEEN))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN");

    if (message instanceof MimeMessage) {
        MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse();

        crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent());
        crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(),
                mimeMessageParser.getPlainContent());
        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName());
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(),
                    dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(null, dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(),
                            parserResult.getParserDocument());
        }
    }
}

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

private void populateMessage(cfSession _Session, Message thisMessage, cfQueryResultData popData, boolean GetAll,
        File attachmentDir, Folder _parent) throws Exception {
    popData.addRow(1);//from   w  ww  .  ja v  a 2  s .c  om
    int Row = popData.getNoRows();

    Date date = thisMessage.getSentDate();
    if (date != null) {
        cfDateData cfdate = new cfDateData(date);
        cfdate.setPOPDate();
        popData.setCell(Row, 1, cfdate);
    } else {
        popData.setCell(Row, 1, new cfStringData(""));
    }

    popData.setCell(Row, 2, new cfStringData(formatAddress(thisMessage.getFrom())));
    popData.setCell(Row, 3, new cfNumberData(thisMessage.getMessageNumber()));
    popData.setCell(Row, 4, new cfStringData(formatAddress(thisMessage.getReplyTo())));
    popData.setCell(Row, 5, new cfStringData(thisMessage.getSubject()));
    popData.setCell(Row, 6,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.CC))));
    popData.setCell(Row, 7,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.TO))));
    String[] msgid = thisMessage.getHeader("Message-ID");
    popData.setCell(Row, 8, new cfStringData(msgid != null ? msgid[0] : ""));
    popData.setCell(Row, 9, new cfStringData(getMessageUID(_parent, thisMessage)));
    popData.setCell(Row, 10, new cfStringData(formatHeader(thisMessage)));

    if (GetAll) {
        retrieveBody(_Session, thisMessage, popData, Row, attachmentDir);
    }
}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index one message./*from   w w  w  .j  av  a2s  . com*/
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}

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

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

    try {/* www  . j  a v a 2s.com*/

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

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

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

        setData("headers", headers);

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

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

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

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

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

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

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

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

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

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

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

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

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

    } catch (Exception E) {
        return false;
    }

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

From source file:com.sonicle.webtop.mail.Service.java

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;//from w  w  w  . java2s . co  m
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset,
        com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
    ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>();
    // Setup fetchprofile to limit the stuff which is fetched 
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);/*ww w  . ja  v a  2s .co  m*/
    fp.add(FetchProfile.Item.FLAGS);
    fp.add(FetchProfile.Item.CONTENT_INFO);
    fp.add(UIDFolder.FetchProfileItem.UID);
    folder.fetch(messages, fp);

    // loop over the fetched messages
    for (int i = 0; i < messages.length && i < offset; i++) {
        org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message();
        Message m = messages[i];
        String from = null;
        if (m.getFrom() != null && m.getFrom().length > 0) {
            from = MessageUtils.decodeText(m.getFrom()[0].toString());
        }
        msg.setFrom(from);

        String replyto = null;
        if (m.getReplyTo() != null && m.getReplyTo().length > 0) {
            replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
        }
        msg.setReplyto(replyto);

        ArrayList<String> to = new ArrayList<String>();
        // Add to addresses
        Address[] toArray = m.getRecipients(RecipientType.TO);
        if (toArray != null) {
            for (Address addr : toArray) {
                String mailTo = MessageUtils.decodeText(addr.toString());
                to.add(mailTo);
            }
        }
        msg.setTo(to);

        // Check if a subject exist and if so decode it
        String subject = m.getSubject();
        if (subject != null) {
            subject = MessageUtils.decodeText(subject);
        }
        msg.setSubject(subject);

        // Add cc addresses
        Address[] ccArray = m.getRecipients(RecipientType.CC);
        ArrayList<String> cc = new ArrayList<String>();
        if (ccArray != null) {
            for (Address addr : ccArray) {
                String mailCc = MessageUtils.decodeText(addr.toString());
                cc.add(mailCc);
            }
        }
        msg.setCc(cc);

        userPreferences.addContact(from);
        userPreferences.addContact(to);
        userPreferences.addContact(replyto);
        userPreferences.addContact(cc);

        // Using sentDate since received date is not useful in the view when using fetchmail
        msg.setReceivedDate(m.getSentDate());

        // Add flags
        ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());

        ArrayList<Tag> tags = new ArrayList<Tag>();
        for (String flag : m.getFlags().getUserFlags()) {
            if (flag.startsWith(Tag.PREFIX)) {
                tags.add(new Tag(flag.substring(Tag.PREFIX.length())));
            }
        }

        msg.setUid(folder.getUID(m));
        msg.setFlags(iFlags);
        msg.setTags(tags);
        try {
            msg.setHasAttachments(hasAttachment(m));
        } catch (MessagingException e) {
            logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
                    + msg.getSubject() + " cause:" + e.getMessage());
            logger.info("");
        }
        mList.add(0, msg);

    }
    return mList;
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//from  w w  w. ja  v a  2  s.  c  om

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    for (int i = 0; i < messages.length; i++) {

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static XContentBuilder toJson(Message message, String riverName, EmailRiverConfig config)
        throws IOException {
    XContentBuilder out = null;//  w  ww  .j ava 2 s  .  co  m
    MimeMessage msg = (MimeMessage) message;
    try {
        List<AttachmentInfo> attachments = null;
        boolean hasAttachment = isContainAttachment(message);
        if (hasAttachment) {
            attachments = saveAttachmentToWeedFs(msg, attachments, config);
        }

        StringBuffer content = new StringBuffer(30);
        getMailTextContent(msg, content);

        int length = 200;
        String summary = delHTMLTag(content.toString());
        summary = (summary.length() > length ? summary.substring(0, length) + "..." : summary);

        out = jsonBuilder().startObject().field("subject", getSubject(msg))
                .field("sent_date", getSentDate(msg, null))
                //                    .field("recv_date", message.getReceivedDate())
                .field("from_mail", convertAddress(message.getFrom()))
                .field("reply_to_mail", convertAddress(message.getReplyTo())).field("from", getFrom(msg))
                .field("to", getReceiveAddress(msg, null)).field("content_type", getContentType(msg))
                .field("summary", summary).field("content", content.toString())
                .field("priority", getPriority(msg)).field("need_receipt", isReplySign(msg))
                .field("size", (msg.getSize() / 1024) + "kb").field("contain_attachment", hasAttachment)
                .field("timestamp", new Date().getTime()).field("via_river", riverName);
        if (attachments != null && attachments.size() > 0) {
            XContentBuilder array = out.field("attachments").startArray();
            for (int i = 0; i < attachments.size(); i++) {
                AttachmentInfo info = attachments.get(i);
                array.startObject().field("file_name", info.fileName).field("file_size", info.fileSize)
                        .field("file_id", info.fileId).field("summary", info.summary).endObject();
            }
            array.endArray();
        }
    } catch (MessagingException e) {
        logger.error("convert mail to json", e);
    }
    assert out != null;
    return out.endObject();
}