Example usage for javax.mail.internet InternetAddress getAddress

List of usage examples for javax.mail.internet InternetAddress getAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getAddress.

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

From source file:com.sonicle.webtop.calendar.CalendarManager.java

private List<String> doEventAttendeeUpdateResponseByRecipient(Connection con, Event event, String recipient,
        EventAttendee.ResponseStatus responseStatus) throws WTException {
    EventDAO evtDao = EventDAO.getInstance();
    EventAttendeeDAO attDao = EventAttendeeDAO.getInstance();

    // Find matching attendees
    ArrayList<String> matchingIds = new ArrayList<>();
    List<OEventAttendee> atts = attDao.selectByEvent(con, event.getEventId());
    for (OEventAttendee att : atts) {
        final InternetAddress ia = InternetAddressUtils.toInternetAddress(att.getRecipient());
        if (ia == null)
            continue;
        if (StringUtils.equalsIgnoreCase(ia.getAddress(), recipient))
            matchingIds.add(att.getAttendeeId());
    }/*from   w w w  . j av a  2 s . c o m*/

    // Update responses
    int ret = attDao.updateAttendeeResponseByIds(con, EnumUtils.toSerializedName(responseStatus), matchingIds);
    evtDao.updateRevision(con, event.getEventId(), BaseDAO.createRevisionTimestamp());
    if (matchingIds.size() == ret) {
        return matchingIds;
    } else {
        throw new WTException("# of attendees to update don't match the uptated ones");
    }
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

private List<RecipientTuple> getInvitationRecipients(UserProfileId ownerProfile, Event event, String crud) {
    ArrayList<RecipientTuple> rcpts = new ArrayList<>();

    // Parameter crud is not used for now!

    if (!event.getAttendees().isEmpty()) {
        String organizerAddress = event.getOrganizerAddress();
        for (EventAttendee attendee : event.getAttendees()) {
            if (!attendee.getNotify())
                continue;
            InternetAddress attendeeIa = attendee.getRecipientInternetAddress();
            if (attendeeIa == null)
                continue;
            if (StringUtils.equalsIgnoreCase(organizerAddress, attendeeIa.getAddress())
                    && !EventAttendee.ResponseStatus.NEEDS_ACTION.equals(attendee.getResponseStatus()))
                continue;

            UserProfileId attProfileId = WT.guessUserProfileIdByEmailAddress(attendeeIa.getAddress());
            rcpts.add(new RecipientTuple(attendeeIa, (attProfileId != null) ? attProfileId : ownerProfile));
        }/*  ww w  .j  av  a2s .c om*/
    }

    return rcpts;
}

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

private Address[] removeDestination(Address a[], String email) throws MessagingException {
    email = email.toLowerCase();//w w w  . ja  v  a  2s . c  o m
    Vector v = new Vector();
    for (int i = 0; i < a.length; ++i) {
        InternetAddress ia = (InternetAddress) a[i];
        if (!ia.getAddress().toLowerCase().equals(email)) {
            v.addElement(a[i]);
        }
    }
    Address na[] = new Address[v.size()];
    v.copyInto(na);
    return na;
}

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

public Identity findIdentity(InternetAddress fromAddr) {
    for (Identity ident : mprofile.getIdentities()) {
        if (fromAddr.getAddress().equalsIgnoreCase(ident.getEmail()))
            return ident;
    }/*www  . j a  v  a  2 s  .  c om*/
    return null;
}

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

public String getDecodedAddress(Address a) {
    String ret = "";
    try {/*from w  ww  .  j  av a  2  s . co  m*/
        InternetAddress ia = (InternetAddress) a;
        String personal = ia.getPersonal();
        String email = ia.getAddress();
        if (personal == null || personal.equals(email)) {
            ret = email;
        } else {
            ret = personal + " <" + email + ">";
        }
    } catch (RuntimeException exc) {
        ret = a.toString();
    }
    return ret;
}

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

public void dmsArchiveMessages(FolderCache from, long nuids[], String idcategory, String idsubcategory,
        boolean fullthreads) throws MessagingException, FileNotFoundException, IOException {
    UserProfile profile = environment.getProfile();
    String archiveto = ss.getDmsArchivePath();
    for (long nuid : nuids) {
        Message msg = from.getMessage(nuid);

        String id = getMessageID(msg);
        if (id.startsWith("<")) {
            id = id.substring(1, id.length() - 1);
        }//from ww w . j a va 2 s . com
        id = id.replaceAll("\\\\", "_");
        id = id.replaceAll("/", "_");
        String filename = archiveto + "/" + id + ".eml";
        String txtname = archiveto + "/" + id + ".txt";
        File file = new File(filename);
        File txtfile = new File(txtname);
        //Only if spool file does not exists
        if (!file.exists()) {

            String emailfrom = "nomail@nodomain.it";
            Address a[] = msg.getFrom();
            if (a != null && a.length > 0) {
                InternetAddress sender = ((InternetAddress) a[0]);
                emailfrom = sender.getAddress();
            }
            String emailto = "nomail@nodomain.it";
            a = msg.getRecipients(Message.RecipientType.TO);
            if (a != null && a.length > 0) {
                InternetAddress to = ((InternetAddress) a[0]);
                emailto = to.getAddress();
            }
            String subject = msg.getSubject();
            java.util.Date date = msg.getReceivedDate();
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(date);
            int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
            int mm = cal.get(java.util.Calendar.MONTH) + 1;
            int yyyy = cal.get(java.util.Calendar.YEAR);
            String sdd = dd < 10 ? "0" + dd : "" + dd;
            String smm = mm < 10 ? "0" + mm : "" + mm;
            String syyyy = "" + yyyy;

            FileOutputStream fos = new FileOutputStream(file);
            msg.writeTo(fos);
            fos.close();

            PrintWriter pw = new PrintWriter(txtfile);
            pw.println(emailfrom);
            pw.println(emailto);
            pw.println(subject);
            pw.println(sdd + "/" + smm + "/" + syyyy);
            pw.println(profile.getUserId());
            pw.println(idcategory);
            pw.println(idsubcategory);
            pw.close();
        }
    }
    from.markDmsArchivedMessages(nuids, fullthreads);
}

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

public void processSendMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    JsonResult json = null;//  w w w  .  ja  v  a2  s. c  o  m
    CoreManager coreMgr = WT.getCoreManager();
    IContactsManager contactsManager = (IContactsManager) WT.getServiceManager("com.sonicle.webtop.contacts",
            true, environment.getProfileId());

    // TODO: Cloud integration!!!
    /*        VFSService vfs=(VFSService)wts.getServiceByName("vfs");
           ArrayList<String> hashlinks=null;
           if (vfs!=null) {
           //look for links to cloud in the html
           String html=request.getParameter("content");
           hashlinks=new ArrayList<String>();
           int hlx=-1;
           String puburl=wtd.getSetting("vfs.pub.url");
           char chars[]=new char[] { '\'', '"'};
           for(char c: chars) {
           String pattern="<a href="+c+puburl+"/public/vfs/";
           Service.logger.debug("Looking for pattern "+pattern);
           while((hlx=html.indexOf(pattern,hlx+1))>=0) {
           int xhash1=hlx+pattern.length();
           int xhash2=html.indexOf(c,xhash1);
           if (xhash2>xhash1) {
           String hash=html.substring(xhash1,xhash2);
           Service.logger.debug("Found hash "+hash);
           hashlinks.add(hash);
           }
           }
           }
           }*/
    try {
        MailAccount account = getAccount(request);
        //String emails[]=request.getParameterValues("recipients");
        Payload<MapItem, JsMessage> pl = ServletUtils.getPayload(request, JsMessage.class);
        JsMessage jsmsg = pl.data;
        long msgId = ServletUtils.getLongParameter(request, "msgId", true);
        boolean isFax = ServletUtils.getBooleanParameter(request, "isFax", false);
        boolean save = ServletUtils.getBooleanParameter(request, "save", false);

        if (isFax) {
            int faxmaxtos = getEnv().getCoreServiceSettings().getFaxMaxRecipients();

            //check for valid fax recipients
            String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern();
            String regex = "^" + faxpattern.replace("{number}", "(\\d+)").replace("{username}", "(\\w+)") + "$";
            Pattern pattern = Pattern.compile(regex);
            int nemails = 0;
            for (JsRecipient jsr : jsmsg.recipients) {
                if (StringUtils.isEmpty(jsr.email))
                    continue;
                ++nemails;
                if (StringUtils.isNumeric(jsr.email))
                    continue;
                boolean matches = false;
                try {
                    InternetAddress ia = new InternetAddress(jsr.email);
                    String email = ia.getAddress();
                    matches = pattern.matcher(email).matches();
                } catch (Exception exc) {

                }
                if (!matches) {
                    throw new Exception(lookupResource(MailLocaleKey.FAX_ADDRESS_ERROR));
                }
            }
            if (faxmaxtos > 0 && nemails > faxmaxtos) {
                throw new WTException(lookupResource(MailLocaleKey.FAX_MAXADDRESS_ERROR), faxmaxtos);
            }

        }

        account.checkStoreConnected();
        //String attachments[] = request.getParameterValues("attachments");
        //if (attachments == null) {
        //   attachments = new String[0];
        //}
        SimpleMessage msg = prepareMessage(jsmsg, msgId, save, isFax);
        Identity ifrom = msg.getFrom();
        String from = environment.getProfile().getEmailAddress();
        if (ifrom != null) {
            from = ifrom.getEmail();
        }
        account.checkStoreConnected();
        Exception exc = sendMessage(msg, jsmsg.attachments);
        if (exc == null) {
            //if is draft, check for deletion
            if (jsmsg.draftuid > 0 && jsmsg.draftfolder != null && ss.isDefaultFolderDraftsDeleteMsgOnSend()) {
                FolderCache fc = account.getFolderCache(jsmsg.draftfolder);
                fc.deleteMessages(new long[] { jsmsg.draftuid }, false);
            }

            //Save used recipients
            for (JsRecipient rcpt : pl.data.recipients) {
                String email = rcpt.email;
                if (email != null && email.trim().length() > 0)
                    coreMgr.autoLearnInternetRecipient(email);
            }

            //Save subject for suggestions
            if (jsmsg.subject != null && jsmsg.subject.trim().length() > 0)
                WT.getCoreManager().addServiceStoreEntry(SERVICE_ID, "subject", jsmsg.subject.toUpperCase(),
                        jsmsg.subject);

            coreMgr.deleteMyAutosaveData(getEnv().getClientTrackingID(), SERVICE_ID, "newmail", "" + msgId);

            deleteAutosavedDraft(account, msgId);
            // TODO: Cloud integration!!! Destination emails added to share
            /*                if (vfs!=null && hashlinks!=null && hashlinks.size()>0) {
                         for(String hash: hashlinks) {
                         Service.logger.debug("Adding emails to hash "+hash);
                         vfs.setAuthEmails(hash, from, emails);
                         }
                    
                         }*/
            FolderCache fc = account.getFolderCache(account.getFolderSent());
            fc.setForceRefresh();
            //check for in-reply-to and set the answered flags
            //String inreplyto = request.getParameter("inreplyto");
            //String replyfolder = request.getParameter("replyfolder");
            //String forwardedfrom = request.getParameter("forwardedfrom");
            //String forwardedfolder = request.getParameter("forwardedfolder");
            //String soriguid=request.getParameter("origuid");
            //long origuid=0;
            //try { origuid=Long.parseLong(soriguid); } catch(RuntimeException rexc) {}
            String foundfolder = null;
            if (jsmsg.forwardedfrom != null && jsmsg.forwardedfrom.trim().length() > 0) {
                try {
                    foundfolder = foundfolder = flagForwardedMessage(account, jsmsg.forwardedfolder,
                            jsmsg.forwardedfrom, jsmsg.origuid);
                } catch (Exception xexc) {
                    Service.logger.error("Exception", xexc);
                }
            } else if ((jsmsg.inreplyto != null && jsmsg.inreplyto.trim().length() > 0)
                    || (jsmsg.replyfolder != null && jsmsg.replyfolder.trim().length() > 0
                            && jsmsg.origuid > 0)) {
                try {

                    String[] toRecipients = SimpleMessage.breakAddr(msg.getTo());

                    for (String toRecipient : toRecipients) {
                        InternetAddress internetAddress = getInternetAddress(toRecipient);
                        String contactEmail = internetAddress.getAddress();
                        String contactPersonal = internetAddress.getPersonal();

                        Condition<ContactQuery> predicate = new ContactQuery().email().eq(contactEmail);

                        List<Integer> myCategories = contactsManager.listCategoryIds();
                        List<Integer> sharedCategories = contactsManager.listIncomingCategoryIds();
                        myCategories.addAll(sharedCategories);

                        boolean existsContact = contactsManager.existContact(myCategories, predicate);

                        if (!existsContact) {
                            sendAddContactMessage(contactEmail, contactPersonal);
                            break;
                        }
                    }

                    foundfolder = flagAnsweredMessage(account, jsmsg.replyfolder, jsmsg.inreplyto,
                            jsmsg.origuid);
                } catch (Exception xexc) {
                    Service.logger.error("Exception", xexc);
                }
            }

            json = new JsonResult().set("foundfolder", foundfolder).set("saved", Boolean.FALSE);
        } else {
            Throwable cause = exc.getCause();
            String msgstr = cause != null ? cause.getMessage() : exc.getMessage();
            json = new JsonResult(false, msgstr);
        }
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        Throwable cause = exc.getCause();
        String msg = cause != null ? cause.getMessage() : exc.getMessage();
        json = new JsonResult(false, msg);
    }
    json.printTo(out);
}

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

public void processPollAdvancedSearch(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//from  w w  w .  j  av  a2 s .  c  o m
    CoreManager core = WT.getCoreManager();

    try {
        MailAccount account = getAccount(request);
        String sstart = request.getParameter("start");
        int start = 0;
        if (sstart != null) {
            start = Integer.parseInt(sstart);
        }
        String sout = "{\n";
        if (ast != null) {
            UserProfile profile = environment.getProfile();
            Locale locale = profile.getLocale();
            java.util.Calendar cal = java.util.Calendar.getInstance(locale);
            ArrayList<Message> msgs = ast.getResult();
            int totalrows = msgs.size();
            int newrows = totalrows - start;
            sout += "total:" + totalrows + ",\nstart:" + start + ",\nlimit:" + newrows + ",\nmessages: [\n";
            boolean first = true;
            for (int i = start; i < msgs.size(); ++i) {
                Message xm = msgs.get(i);
                if (xm.isExpunged()) {
                    continue;
                }
                IMAPFolder xmfolder = (IMAPFolder) xm.getFolder();
                boolean wasopen = xmfolder.isOpen();
                if (!wasopen)
                    xmfolder.open(Folder.READ_ONLY);
                long nuid = xmfolder.getUID(xm);
                if (!wasopen)
                    xmfolder.close(false);
                IMAPMessage m = (IMAPMessage) xm;
                //Date
                java.util.Date d = m.getSentDate();
                if (d == null) {
                    d = m.getReceivedDate();
                }
                if (d == null) {
                    d = new java.util.Date(0);
                }
                cal.setTime(d);
                int yyyy = cal.get(java.util.Calendar.YEAR);
                int mm = cal.get(java.util.Calendar.MONTH);
                int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
                int hhh = cal.get(java.util.Calendar.HOUR_OF_DAY);
                int mmm = cal.get(java.util.Calendar.MINUTE);
                int sss = cal.get(java.util.Calendar.SECOND);
                String xfolder = xm.getFolder().getFullName();
                FolderCache fc = account.getFolderCache(xfolder);
                String folder = StringEscapeUtils.escapeEcmaScript(xfolder);
                String foldername = StringEscapeUtils
                        .escapeEcmaScript(MailUtils.htmlescape(getInternationalFolderName(fc)));
                //From
                String from = "";
                Address ia[] = m.getFrom();
                if (ia != null) {
                    InternetAddress iafrom = (InternetAddress) ia[0];
                    from = iafrom.getPersonal();
                    if (from == null) {
                        from = iafrom.getAddress();
                    }
                }
                from = (from == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                //To
                String to = "";
                ia = m.getRecipients(Message.RecipientType.TO);
                if (ia != null) {
                    InternetAddress iato = (InternetAddress) ia[0];
                    to = iato.getPersonal();
                    if (to == null) {
                        to = iato.getAddress();
                    }
                }
                to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                //Subject
                String subject = m.getSubject();
                if (subject != null) {
                    try {
                        subject = MailUtils.decodeQString(subject);
                    } catch (Exception exc) {

                    }
                }
                subject = (subject == null ? ""
                        : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)));
                //Unread
                boolean unread = !m.isSet(Flags.Flag.SEEN);
                //if (ppattern==null && unread) ++funread;
                //Priority
                int priority = getPriority(m);
                //Status
                java.util.Date today = new java.util.Date();
                java.util.Calendar cal1 = java.util.Calendar.getInstance(locale);
                java.util.Calendar cal2 = java.util.Calendar.getInstance(locale);
                boolean isToday = false;
                if (d != null) {
                    cal1.setTime(today);
                    cal2.setTime(d);
                    if (cal1.get(java.util.Calendar.DAY_OF_MONTH) == cal2.get(java.util.Calendar.DAY_OF_MONTH)
                            && cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                            && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                        isToday = true;
                    }
                }

                Flags flags = m.getFlags();
                String status = "read";
                if (flags != null) {
                    if (flags.contains(Flags.Flag.ANSWERED)) {
                        if (flags.contains("$Forwarded")) {
                            status = "repfwd";
                        } else {
                            status = "replied";
                        }
                    } else if (flags.contains("$Forwarded")) {
                        status = "forwarded";
                    } else if (flags.contains(Flags.Flag.SEEN)) {
                        status = "read";
                    } else if (isToday) {
                        status = "new";
                    } else {
                        status = "unread";
                    }
                    //                    if (flags.contains(Flags.Flag.USER)) flagImage=webtopapp.getUri()+"/images/themes/"+profile.getTheme()+"/mail/flag.gif";
                }
                //Size
                int msgsize = 0;
                msgsize = (m.getSize() * 3) / 4;// /1024 + 1;
                //User flags
                String cflag = "";
                for (WebtopFlag webtopFlag : webtopFlags) {
                    String flagstring = webtopFlag.label;
                    //String tbflagstring=webtopFlag.tbLabel;
                    if (!flagstring.equals("complete")) {
                        String oldflagstring = "flag" + flagstring;
                        if (flags.contains(flagstring) || flags.contains(oldflagstring)
                        /*|| (tbflagstring!=null && flags.contains(tbflagstring))*/
                        ) {
                            cflag = flagstring;
                        }
                    }
                }
                boolean flagComplete = flags.contains("complete");
                if (flagComplete) {
                    cflag += "-complete";
                }

                //idmessage=idmessage.replaceAll("\\\\", "\\\\");
                //idmessage=OldUtils.jsEscape(idmessage);
                if (!first) {
                    sout += ",\n";
                }
                boolean archived = false;
                if (hasDmsDocumentArchiving()) {
                    archived = m.getHeader("X-WT-Archived") != null;
                    if (!archived) {
                        archived = flags.contains(sflagDmsArchived);
                    }
                }

                boolean hasNote = flags.contains(sflagNote);

                sout += "{folder:'" + folder + "', folderdesc:'" + foldername + "',idmandfolder:'" + folder
                        + "|" + nuid + "',idmessage:'" + nuid + "',priority:" + priority + ",status:'" + status
                        + "',to:'" + to + "',from:'" + from + "',subject:'" + subject + "',date: new Date("
                        + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),unread: " + unread
                        + ",size:" + msgsize + ",flag:'" + cflag + "'" + (archived ? ",arch:true" : "")
                        + (isToday ? ",istoday:true" : "") + (hasNote ? ",note:true" : "") + "}";
                first = false;
            }
            sout += "\n]\n, progress: " + ast.getProgress() + ", curfoldername: '"
                    + StringEscapeUtils.escapeEcmaScript(getInternationalFolderName(ast.getCurrentFolder()))
                    + "', " + "max: " + ast.isMoreThanMax() + ", finished: "
                    + (ast.isFinished() || ast.isCanceled() || !ast.isRunning()) + " }\n";
        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n] }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processGetEditMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;//from www . j ava 2 s.c om
    try {
        MailEditFormat editFormat = ServletUtils.getEnumParameter(request, "format", null,
                MailEditFormat.class);
        if (editFormat == null)
            editFormat = EnumUtils.forSerializedName(us.getFormat(), MailEditFormat.HTML, MailEditFormat.class);
        boolean isPlainEdit = MailEditFormat.PLAIN_TEXT.equals(editFormat);

        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        IMAPMessage m = (IMAPMessage) mcache.getMessage(Long.parseLong(puidmessage));
        m.setPeek(us.isManualSeen());
        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        String vheader[] = m.getHeader("Disposition-Notification-To");
        boolean receipt = false;
        int priority = 3;
        boolean recipients = false;
        boolean toDelete = false;
        if (account.isDraftsFolder(pfoldername)) {
            if (vheader != null && vheader[0] != null) {
                receipt = true;
            }
            priority = getPriority(m);
            recipients = true;

            //if autosaved drafts, delete
            String values[] = m.getHeader(HEADER_X_WEBTOP_MSGID);
            if (values != null && values.length > 0) {
                try {
                    long msgId = Long.parseLong(values[0]);
                    if (msgId > 0) {
                        toDelete = true;
                    }
                } catch (NumberFormatException exc) {

                }
            }
        }

        sout = "{\n result: true,";
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        }
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String inreplyto = null;
        String references[] = null;
        String vs[] = m.getHeader("In-Reply-To");
        if (vs != null && vs[0] != null) {
            inreplyto = vs[0];
        }
        references = m.getHeader("References");
        if (inreplyto != null) {
            vs = m.getHeader("Sonicle-reply-folder");
            String replyfolder = null;
            if (vs != null && vs[0] != null) {
                replyfolder = vs[0];
            }
            if (replyfolder != null) {
                sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(replyfolder) + "',";
            }
            sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',";
        }
        if (references != null) {
            String refs = "";
            for (String s : references) {
                refs += StringEscapeUtils.escapeEcmaScript(s) + " ";
            }
            sout += " references: '" + refs.trim() + "',";
        }

        String forwardedfrom = null;
        vs = m.getHeader("Forwarded-From");
        if (vs != null && vs[0] != null) {
            forwardedfrom = vs[0];
        }
        if (forwardedfrom != null) {
            vs = m.getHeader("Sonicle-forwarded-folder");
            String forwardedfolder = null;
            if (vs != null && vs[0] != null) {
                forwardedfolder = vs[0];
            }
            if (forwardedfolder != null) {
                sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(forwardedfolder) + "',";
            }
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }

        sout += " receipt: " + receipt + ",\n";
        sout += " priority: " + (priority >= 3 ? false : true) + ",\n";

        Identity ident = null;
        Address from[] = m.getFrom();
        InternetAddress iafrom = null;
        if (from != null && from.length > 0) {
            iafrom = (InternetAddress) from[0];
            String email = iafrom.getAddress();
            String displayname = iafrom.getPersonal();
            if (displayname == null)
                displayname = email;
            //sout+=" from: { email: '"+StringEscapeUtils.escapeEcmaScript(email)+"', displayname: '"+StringEscapeUtils.escapeEcmaScript(displayname)+"' },\n";
            ident = mprofile.getIdentity(displayname, email);
        }

        sout += " recipients: [\n";
        if (recipients) {
            Address tos[] = m.getRecipients(RecipientType.TO);
            String srec = "";
            if (tos != null) {
                for (Address to : tos) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'to', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(to)) + "'" + " }";
                }
            }
            Address ccs[] = m.getRecipients(RecipientType.CC);
            if (ccs != null) {
                for (Address cc : ccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'cc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(cc)) + "'" + " }";
                }
            }
            Address bccs[] = m.getRecipients(RecipientType.BCC);
            if (bccs != null) {
                for (Address bcc : bccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'bcc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(bcc)) + "'" + " }";
                }
            }

            sout += srec;
        } else {
            sout += "   { " + "rtype: 'to', " + "email: ''" + " }";

        }
        sout += " ],\n";

        String html = "";
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        ArrayList<String> htmlparts = mcache.getHTMLParts((MimeMessage) m, newmsgid, true, balanceTags);
        for (String xhtml : htmlparts) {
            html += xhtml + "<BR><BR>";
        }
        HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
        //if(!wasseen){
        //   if (us.isManualSeen()) {
        //      m.setFlag(Flags.Flag.SEEN, false);
        //   }
        //}

        boolean first = true;
        sout += " attachments: [\n";
        for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
            Part part = maildata.getAttachmentPart(i);
            String filename = getPartName(part);

            String cids[] = part.getHeader("Content-ID");
            String cid = null;
            //String cid=filename;
            if (cids != null && cids[0] != null) {
                cid = cids[0];
                if (cid.startsWith("<"))
                    cid = cid.substring(1);
                if (cid.endsWith(">"))
                    cid = cid.substring(0, cid.length() - 1);
            }

            if (filename == null) {
                filename = cid;
            }
            String mime = part.getContentType();
            UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream());
            boolean inline = false;
            if (part.getDisposition() != null) {
                inline = part.getDisposition().equalsIgnoreCase(Part.INLINE);
            }
            if (!first) {
                sout += ",\n";
            }
            sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', "
                    + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: "
                    + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", "
                    + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + " " + " }";
            first = false;
            //TODO: change this weird matching of cids2urls!
            html = StringUtils.replace(html, "cid:" + cid,
                    "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID
                            + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId()
                            + "&cid=" + cid);

        }
        sout += "\n ],\n";

        if (ident != null)
            sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        sout += " deleted:" + toDelete + ",\n";
        sout += " folder:'" + pfoldername + "',\n";
        sout += " content:'" + (isPlainEdit
                ? StringEscapeUtils.escapeEcmaScript(MailUtils.htmlToText(MailUtils.htmlunescapesource(html)))
                : StringEscapeUtils.escapeEcmaScript(html)) + "',\n";
        sout += " format:'" + EnumUtils.toSerializedName(editFormat) + "'\n";
        sout += "\n}";

        m.setPeek(false);

        if (toDelete) {
            m.setFlag(Flags.Flag.DELETED, true);
            m.getFolder().expunge();
        }

        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
}

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

private SimpleMessage prepareMessage(JsMessage jsmsg, long msgId, boolean save, boolean isFax)
        throws Exception {
    PrivateEnvironment env = environment;
    UserProfile profile = env.getProfile();
    //expand multiple addresses
    ArrayList<String> aemails = new ArrayList<>();
    ArrayList<String> artypes = new ArrayList<>();
    for (JsRecipient jsrcpt : jsmsg.recipients) {
        String emails[] = StringUtils.split(jsrcpt.email, ';');
        for (String email : emails) {
            aemails.add(email);/*from w  w w  . j  a va  2 s.c om*/
            artypes.add(jsrcpt.rtype);
        }
    }
    String emails[] = new String[aemails.size()];
    emails = (String[]) aemails.toArray(emails);
    String rtypes[] = new String[artypes.size()];
    rtypes = (String[]) artypes.toArray(rtypes);

    //String replyfolder = request.getParameter("replyfolder");
    //String inreplyto = request.getParameter("inreplyto");
    //String references = request.getParameter("references");

    //String forwardedfolder = request.getParameter("forwardedfolder");
    //String forwardedfrom = request.getParameter("forwardedfrom");

    //String subject = request.getParameter("subject");
    //String mime = request.getParameter("mime");
    //String sident = request.getParameter("identity");
    //String content = request.getParameter("content");
    //String msgid = request.getParameter("newmsgid");
    //String ssave = request.getParameter("save");
    //boolean save = (ssave != null && ssave.equals("true"));
    //String sreceipt = request.getParameter("receipt");
    //boolean receipt = (sreceipt != null && sreceipt.equals("true"));
    //String spriority = request.getParameter("priority");
    //boolean priority = (spriority != null && spriority.equals("true"));

    //boolean isFax = request.getParameter("fax") != null;

    String to = null;
    String cc = null;
    String bcc = null;
    for (int i = 0; i < emails.length; ++i) {
        //String email=decoder.decode(ByteBuffer.wrap(emails[i].getBytes())).toString();
        String email = emails[i];
        if (email == null || email.trim().length() == 0) {
            continue;
        }
        //Check for list
        boolean checkemail = true;
        boolean listdone = false;
        if (email.indexOf('@') < 0) {
            if (isFax && StringUtils.isNumeric(email)) {
                String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern();
                String faxemail = faxpattern.replace("{number}", email).replace("{username}",
                        profile.getUserId());
                email = faxemail;
            }
        } else {
            //check for list if one email with domain equals one allowed service id
            InternetAddress ia = null;
            try {
                ia = new InternetAddress(email);
            } catch (AddressException exc) {

            }
            if (ia != null) {
                String iamail = ia.getAddress();
                String dom = iamail.substring(iamail.indexOf("@") + 1);
                CoreManager core = WT.getCoreManager();
                if (environment.getSession().isServiceAllowed(dom)) {
                    List<Recipient> rcpts = core.expandVirtualProviderRecipient(iamail);
                    for (Recipient rcpt : rcpts) {
                        String xemail = rcpt.getAddress();
                        String xpersonal = rcpt.getPersonal();
                        String xrtype = EnumUtils.toSerializedName(rcpt.getType());

                        if (xpersonal != null)
                            xemail = xpersonal + " <" + xemail + ">";

                        try {
                            checkEmail(xemail);
                            InternetAddress.parse(xemail.replace(',', ' '), true);
                        } catch (AddressException exc) {
                            throw new AddressException(
                                    lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + xemail);
                        }
                        if (rtypes[i].equals("to")) {
                            if (xrtype.equals("to")) {
                                if (to == null)
                                    to = xemail;
                                else
                                    to += "; " + xemail;
                            } else if (xrtype.equals("cc")) {
                                if (cc == null)
                                    cc = xemail;
                                else
                                    cc += "; " + xemail;
                            } else if (xrtype.equals("bcc")) {
                                if (bcc == null)
                                    bcc = xemail;
                                else
                                    bcc += "; " + xemail;
                            }
                        } else if (rtypes[i].equals("cc")) {
                            if (cc == null)
                                cc = xemail;
                            else
                                cc += "; " + xemail;
                        } else if (rtypes[i].equals("bcc")) {
                            if (bcc == null)
                                bcc = xemail;
                            else
                                bcc += "; " + xemail;
                        }

                        listdone = true;
                        checkemail = false;
                    }
                }
            }
        }
        if (listdone) {
            continue;
        }

        if (checkemail) {
            try {
                checkEmail(email);
                //InternetAddress.parse(email.replace(',', ' '), false);
                getInternetAddress(email);
            } catch (AddressException exc) {
                Service.logger.error("Exception", exc);
                throw new AddressException(lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + email);
            }
        }

        if (rtypes[i].equals("to")) {
            if (to == null) {
                to = email;
            } else {
                to += "; " + email;
            }
        } else if (rtypes[i].equals("cc")) {
            if (cc == null) {
                cc = email;
            } else {
                cc += "; " + email;
            }
        } else if (rtypes[i].equals("bcc")) {
            if (bcc == null) {
                bcc = email;
            } else {
                bcc += "; " + email;
            }
        }
    }

    //long id = Long.parseLong(msgid);
    SimpleMessage msg = new SimpleMessage(msgId);
    /*int idx = jsmsg.identity - 1;
    Identity from = null;
    if (idx >= 0) {
       from = mprofile.getIdentity(idx);
    }*/
    Identity from = mprofile.getIdentity(jsmsg.identityId);
    msg.setFrom(from);
    msg.setTo(to);
    msg.setCc(cc);
    msg.setBcc(bcc);
    msg.setSubject(jsmsg.subject);

    //TODO: fax coverpage - dismissed
    /*if (isFax) {
       String coverpage = request.getParameter("faxcover");
       if (coverpage != null) {
    if (coverpage.equals("none")) {
       msg.addHeaderLine("X-FAX-AutoCoverPage: No");
    } else {
       msg.addHeaderLine("X-FAX-AutoCoverPage: Yes");
       msg.addHeaderLine("X-FAX-Cover-Template: " + coverpage);
    }
       }
    }*/

    //TODO: custom headers keys
    /*String[] headersKeys = request.getParameterValues("headersKeys");
    String[] headersValues = request.getParameterValues("headersValues");
    if (headersKeys != null && headersValues != null && headersKeys.length == headersValues.length) {
       for (int i = 0; i < headersKeys.length; i++) {
    if (!headersKeys[i].equals("")) {
       msg.addHeaderLine(headersKeys[i] + ": " + headersValues[i]);
    }
       }
    }*/

    if (jsmsg.inreplyto != null) {
        msg.setInReplyTo(jsmsg.inreplyto);
    }
    if (jsmsg.references != null) {
        msg.setReferences(new String[] { jsmsg.references });
    }
    if (jsmsg.replyfolder != null) {
        msg.setReplyFolder(jsmsg.replyfolder);
    }

    if (jsmsg.forwardedfolder != null) {
        msg.setForwardedFolder(jsmsg.forwardedfolder);
    }
    if (jsmsg.forwardedfrom != null) {
        msg.setForwardedFrom(jsmsg.forwardedfrom);
    }

    msg.setReceipt(jsmsg.receipt);
    msg.setPriority(jsmsg.priority ? 1 : 3);
    if (jsmsg.format == null || jsmsg.format.equals("plain")) {
        msg.setContent(jsmsg.content);
    } else {
        if (jsmsg.format.equalsIgnoreCase("html")) {
            //TODO: change this weird matching of cids2urls!

            //CIDs
            String content = jsmsg.content;
            String pattern1 = RegexUtils
                    .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&amp;service="
                            + SERVICE_ID + "&amp;action=PreviewAttachment&amp;nowriter=true&amp;uploadId=");
            String pattern2 = RegexUtils.escapeRegexSpecialChars("&amp;cid=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:");
            pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken()
                    + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&cid=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:");

            //URLs
            pattern1 = RegexUtils
                    .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&amp;service="
                            + SERVICE_ID + "&amp;action=PreviewAttachment&amp;nowriter=true&amp;uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&amp;url=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "");
            pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken()
                    + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=");
            pattern2 = RegexUtils.escapeRegexSpecialChars("&url=");
            content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "");

            //My resources as cids?
            if (ss.isPublicResourceLinksAsInlineAttachments()) {
                ArrayList<JsAttachment> rescids = new ArrayList<>();
                String match = "\"" + URIUtils.concat(getEnv().getCoreServiceSettings().getPublicBaseUrl(),
                        ResourceRequest.URL);
                while (StringUtils.contains(content, match)) {
                    pattern1 = RegexUtils.escapeRegexSpecialChars(match);
                    Pattern pattern = Pattern.compile(pattern1 + "\\S*");
                    Matcher matcher = pattern.matcher(content);
                    matcher.find();
                    String matched = matcher.group();
                    String url = matched.substring(1, matched.length() - 1);
                    URI uri = new URI(url);

                    // Retrieve macthed URL 
                    // and save it locally
                    logger.debug("Downloading resource file as uploaded file from URL [{}]", url);
                    HttpClient httpCli = null;
                    try {
                        httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(),
                                uri);
                        InputStream is = HttpClientUtils.getContent(httpCli, uri);
                        String tag = "" + msgId;
                        String filename = PathUtils.getFileName(uri.getPath());
                        UploadedFile ufile = addAsUploadedFile(tag, filename,
                                ServletHelper.guessMediaType(filename), is);
                        rescids.add(new JsAttachment(ufile.getUploadId(), filename, ufile.getUploadId(), true,
                                ufile.getSize()));
                        content = matcher.replaceFirst("\"cid:" + ufile.getUploadId() + "\"");
                    } catch (IOException ex) {
                        throw new WTException(ex, "Unable to retrieve webcal [{0}]", uri);
                    } finally {
                        HttpClientUtils.closeQuietly(httpCli);
                    }
                }

                //add new resource cids as attachments
                if (rescids.size() > 0) {
                    if (jsmsg.attachments == null)
                        jsmsg.attachments = new ArrayList<>();
                    jsmsg.attachments.addAll(rescids);
                }
            }

            String textcontent = MailUtils.HtmlToText_convert(MailUtils.htmlunescapesource(content));
            String htmlcontent = MailUtils.htmlescapefixsource(content).trim();
            if (htmlcontent.length() < 6 || !htmlcontent.substring(0, 6).toLowerCase().equals("<html>")) {
                htmlcontent = "<html><header></header><body>" + htmlcontent + "</body></html>";
            }
            msg.setContent(htmlcontent, textcontent, "text/html");
        } else {
            msg.setContent(jsmsg.content, null, "text/" + jsmsg.format);
        }

    }
    return msg;
}