Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

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

Prototype

public MessagingException(String s) 

Source Link

Document

Constructs a MessagingException with the specified detail message.

Usage

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//  w  w w.ja  va  2 s .  c o m
 *
 * @param buffer DOCUMENT ME!
 * @param bytes DOCUMENT ME!
 * @param breakLine DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer decodeTextPlain(StringBuffer buffer, byte[] bytes, String breakLine, String charset)
        throws MessagingException {
    // pick off the individual lines of text
    // and append to the buffer
    String aux = null;

    try {
        aux = new String(bytes, charset).replaceAll("\n", breakLine);

        //aux = JavaScriptFilter.apply(aux);
    } catch (UnsupportedEncodingException e) {
        new MessagingException(e.getMessage());
    }

    buffer.append(aux);

    return buffer;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from w w  w  . j a  va  2  s  . com
 *
 * @param part DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static BufferedReader getTextReader(Part part, String charset) throws MessagingException {
    try {
        InputStream xis = part.getInputStream(); // transfer decoded only

        // now construct a reader from the decoded stream
        return MessageUtilities.getTextReader(xis, charset);
    } catch (IOException xex) {
        throw new MessagingException(xex.toString());
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get the content dispostion of a part. The part is interogated for a
 * valid content disposition. If the content disposition is missing, a
 * default disposition is created based on the type of the part.
 *
 * @param part The part to interogate/*from  w  ww .j  a v a  2  s.  co m*/
 *
 * @return ContentDisposition of the part
 *
 * @throws MessagingException DOCUMENT ME!
 *
 * @see javax.mail.Part
 */
public static ContentDisposition getContentDisposition(Part part) throws MessagingException {
    String[] xheaders = part.getHeader("Content-Disposition");

    try {
        if (xheaders != null) {
            return new ContentDisposition(xheaders[0]);
        }
    } catch (ParseException xex) {
        throw new MessagingException(xex.toString());
    }

    // set default disposition based on part type
    if (part instanceof MimeBodyPart) {
        return new ContentDisposition("attachment");
    }

    return new ContentDisposition("inline");
}

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

public void processGetReplyMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    UserProfile profile = environment.getProfile();
    //WebTopApp webtopapp=environment.getWebTopApp();
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String preplyall = request.getParameter("replyall");
    boolean replyAll = false;
    if (preplyall != null && preplyall.equals("1")) {
        replyAll = true;/*from  w  ww  .j  av a  2  s . c o m*/
    }
    String sout = null;
    try {
        String format = us.getFormat();
        boolean isHtml = format.equals("html");
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        Message m = mcache.getMessage(Long.parseLong(puidmessage));
        if (m.isExpunged()) {
            throw new MessagingException("Message " + puidmessage + " expunged");
        }
        int newmsgid = getNewMessageID();
        SimpleMessage smsg = getReplyMsg(getNewMessageID(), account, m, replyAll,
                account.isSentFolder(pfoldername), isHtml, profile.getEmailAddress(),
                mprofile.isIncludeMessageInReply(), lookupResource(MailLocaleKey.MSG_FROMTITLE),
                lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE),
                lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE));
        sout = "{\n result: true,";
        Identity ident = mprofile.getIdentity(pfoldername);
        String inreplyto = smsg.getInReplyTo();
        String references[] = smsg.getReferences();
        sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',";
        if (inreplyto != null) {
            sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',";
        }
        if (references != null) {
            String refs = "";
            for (String s : references) {
                refs += StringEscapeUtils.escapeEcmaScript(s) + " ";
            }
            sout += " references: '" + refs.trim() + "',";
        }
        String subject = smsg.getSubject();
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";
        sout += " recipients: [\n";
        String tos[] = smsg.getTo().split(";");
        boolean first = true;
        for (String to : tos) {
            if (!first) {
                sout += ",\n";
            }
            sout += "   {rtype:'to',email:'" + StringEscapeUtils.escapeEcmaScript(to) + "'}";
            first = false;
        }
        String ccs[] = smsg.getCc().split(";");
        for (String cc : ccs) {
            if (!first) {
                sout += ",\n";
            }
            sout += "   {rtype:'cc',email:'" + StringEscapeUtils.escapeEcmaScript(cc) + "'}";
            first = false;
        }
        sout += "\n ],\n";
        sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        if (isHtml) {
            String html = smsg.getContent();

            //cid inline attachments and relative html href substitution
            HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
            first = true;
            sout += " attachments: [\n";

            for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
                try {
                    Part part = maildata.getAttachmentPart(i);
                    String filename = getPartName(part);
                    String cids[] = part.getHeader("Content-ID");
                    if (cids != null && cids[0] != null) {
                        String cid = cids[0];
                        if (cid.startsWith("<"))
                            cid = cid.substring(1);
                        if (cid.endsWith(">"))
                            cid = cid.substring(0, cid.length() - 1);
                        String mime = MailUtils.getMediaTypeFromHeader(part.getContentType());
                        UploadedFile upfile = addAsUploadedFile("" + newmsgid, filename, mime,
                                part.getInputStream());
                        if (!first) {
                            sout += ",\n";
                        }
                        sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId())
                                + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', "
                                + " cid: '" + StringEscapeUtils.escapeEcmaScript(cid) + "', "
                                + " inline: true, " + " fileSize: " + upfile.getSize() + ", " + " editable: "
                                + isFileEditableInDocEditor(filename) + " " + " }";
                        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);
                    }
                } catch (Exception exc) {
                    Service.logger.error("Exception", exc);
                }
            }

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

            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n";
        } else {
            String text = smsg.getTextContent();
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n";
        }
        sout += " format:'" + format + "'\n";
        sout += "\n}";
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
    if (sout != null) {
        out.println(sout);
    }
}

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

public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//ww w.ja  v  a  2 s .  com
    MailAccount account = getAccount(request);
    UserProfile profile = environment.getProfile();
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    String pattached = request.getParameter("attached");
    boolean attached = (pattached != null && pattached.equals("1"));
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;
    try {
        String format = us.getFormat();
        boolean isHtml = format.equals("html");
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        Message m = mcache.getMessage(Long.parseLong(puidmessage));
        if (m.isExpunged()) {
            throw new MessagingException("Message " + puidmessage + " expunged");
        }
        SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE),
                lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE),
                lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE),
                attached);

        sout = "{\n result: true,";
        Identity ident = mprofile.getIdentity(pfoldername);
        String forwardedfrom = smsg.getForwardedFrom();
        sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',";
        if (forwardedfrom != null) {
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }
        String subject = smsg.getSubject();
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String html = smsg.getContent();
        String text = smsg.getTextContent();
        if (!attached) {
            HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
            boolean first = true;
            sout += " attachments: [\n";

            for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
                try {
                    Part part = maildata.getAttachmentPart(i);
                    String filename = getPartName(part);
                    if (!part.isMimeType("message/*")) {
                        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 = MailUtils.getMediaTypeFromHeader(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() + ", "
                                + " editable: " + isFileEditableInDocEditor(filename) + " " + " }";
                        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);
                    }
                } catch (Exception exc) {
                    Service.logger.error("Exception", exc);
                }
            }

            sout += "\n ],\n";
            //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid=";
            //html = replaceCidUrls(html, maildata, surl);
        } else {
            String filename = m.getSubject() + ".eml";
            UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822",
                    ((IMAPMessage) m).getMimeStream());
            sout += " attachments: [\n";
            sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', "
                    + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, "
                    + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: "
                    + isFileEditableInDocEditor(filename) + " " + " }";
            sout += "\n ],\n";
        }
        sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        if (isHtml) {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n";
        } else {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n";
        }
        sout += " format:'" + format + "'\n";
        sout += "\n}";
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
        out.println(sout);
    }
}

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

public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String nopec = request.getParameter("nopec");
    int idattach = 0;
    boolean isEditor = request.getParameter("editor") != null;
    boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true);

    if (df == null) {
        df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
                environment.getProfile().getLocale());
    }/*from  w  w w  . jav  a  2  s  .co  m*/
    try {
        FolderCache mcache = null;
        Message m = null;
        IMAPMessage im = null;
        int recs = 0;
        long msguid = -1;
        String vheader[] = null;
        boolean wasseen = false;
        boolean isPECView = false;
        String sout = "{\nmessage: [\n";
        if (providername == null) {
            account.checkStoreConnected();
            mcache = account.getFolderCache(pfoldername);
            msguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(msguid);
            im = (IMAPMessage) m;
            im.setPeek(us.isManualSeen());
            if (m.isExpunged())
                throw new MessagingException("Message " + puidmessage + " expunged");
            vheader = m.getHeader("Disposition-Notification-To");
            wasseen = m.isSet(Flags.Flag.SEEN);
            if (pidattach != null) {

                HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
                m = (Message) part.getContent();
                idattach = Integer.parseInt(pidattach) + 1;
            } else if (nopec == null && mcache.isPEC()) {
                String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO);
                if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) {
                    HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                    int parts = mailData.getAttachmentPartCount();
                    for (int i = 0; i < parts; ++i) {
                        Part p = mailData.getAttachmentPart(i);
                        if (p.isMimeType("message/rfc822")) {
                            m = (Message) p.getContent();
                            idattach = i + 1;
                            isPECView = true;
                            break;
                        }
                    }
                }
            }
        } else {
            // TODO: provider get message!!!!
            /*                WebTopService provider=wts.getServiceByName(providername);
                         MessageContentProvider mcp=provider.getMessageContentProvider(providerid);
                         m=new MimeMessage(session,mcp.getSource());
                         mcache=fcProvided;
                         mcache.addProvidedMessage(providername, providerid, m);*/
        }
        String messageid = getMessageID(m);
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        } else {
            try {
                subject = MailUtils.decodeQString(subject);
            } catch (Exception exc) {

            }
        }
        java.util.Date d = m.getSentDate();
        if (d == null) {
            d = m.getReceivedDate();
        }
        if (d == null) {
            d = new java.util.Date(0);
        }
        String date = df.format(d).replaceAll("\\.", ":");
        String fromName = "";
        String fromEmail = "";
        Address as[] = m.getFrom();
        InternetAddress iafrom = null;
        if (as != null && as.length > 0) {
            iafrom = (InternetAddress) as[0];
            fromName = iafrom.getPersonal();
            fromEmail = adjustEmail(iafrom.getAddress());
            if (fromName == null) {
                fromName = fromEmail;
            }
        }
        sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName))
                + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n";
        recs += 2;
        Address tos[] = m.getRecipients(RecipientType.TO);
        if (tos != null) {
            for (Address to : tos) {
                InternetAddress ia = (InternetAddress) to;
                String toName = ia.getPersonal();
                String toEmail = adjustEmail(ia.getAddress());
                if (toName == null) {
                    toName = toEmail;
                }
                sout += "{iddata:'to',value1:'"
                        + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address ccs[] = m.getRecipients(RecipientType.CC);
        if (ccs != null) {
            for (Address cc : ccs) {
                InternetAddress ia = (InternetAddress) cc;
                String ccName = ia.getPersonal();
                String ccEmail = adjustEmail(ia.getAddress());
                if (ccName == null) {
                    ccName = ccEmail;
                }
                sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address bccs[] = m.getRecipients(RecipientType.BCC);
        if (bccs != null)
            for (Address bcc : bccs) {
                InternetAddress ia = (InternetAddress) bcc;
                String bccName = ia.getPersonal();
                String bccEmail = adjustEmail(ia.getAddress());
                if (bccName == null) {
                    bccName = bccEmail;
                }
                sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n";
                ++recs;
            }
        ArrayList<String> htmlparts = null;
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        if (providername == null) {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags);
        } else {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        ICalendarRequest ir = mailData.getICalRequest();
        if (ir != null) {
            if (htmlparts.size() > 0)
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0))
                        + "',value2:'',value3:0},\n";
        } else {
            for (String html : htmlparts) {
                //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n";
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html)
                        + "',value2:'',value3:0},\n";
                ++recs;
            }
        }

        /*if (!wasseen) {
           //if (us.isManualSeen()) {
           if (!setSeen) {
              m.setFlag(Flags.Flag.SEEN, false);
           } else {
              //if no html part, flag seen is not set
              if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true);
           }
        }*/
        if (!us.isManualSeen()) {
            if (htmlparts.size() == 0)
                m.setFlag(Flags.Flag.SEEN, true);
        } else {
            if (setSeen)
                m.setFlag(Flags.Flag.SEEN, true);
        }

        int acount = mailData.getAttachmentPartCount();
        for (int i = 0; i < acount; ++i) {
            Part p = mailData.getAttachmentPart(i);
            String ctype = p.getContentType();
            Service.logger.debug("attachment " + i + " is " + ctype);
            int ix = ctype.indexOf(';');
            if (ix > 0) {
                ctype = ctype.substring(0, ix);
            }
            String cidnames[] = p.getHeader("Content-ID");
            String cidname = null;
            if (cidnames != null && cidnames.length > 0)
                cidname = mcache.normalizeCidFileName(cidnames[0]);
            boolean isInlineable = isInlineableMime(ctype);
            boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable;
            if (inline && cidname != null)
                inline = mailData.isReferencedCid(cidname);
            if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) {
                continue;
            }

            String imgname = null;
            boolean isCalendar = ctype.equalsIgnoreCase("text/calendar")
                    || ctype.equalsIgnoreCase("text/icalendar");
            if (isCalendar) {
                imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel()
                        + "/ical_16.png";
            }

            String pname = getPartName(p);
            try {
                pname = MailUtils.decodeQString(pname);
            } catch (Exception exc) {
            }
            if (pname == null) {
                ix = ctype.indexOf("/");
                String fname = ctype;
                if (ix > 0) {
                    fname = ctype.substring(ix + 1);
                }
                //String ext = WT.getMediaTypeExtension(ctype);
                //if (ext == null) {
                pname = fname;
                //} else {
                //   pname = fname + "." + ext;
                //}
                if (isCalendar)
                    pname += ".ics";
            } else {
                if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics"))
                    pname += ".ics";
            }
            int size = p.getSize();
            int lines = (size / 76);
            int rsize = size - (lines * 2);//(p.getSize()/4)*3;
            String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml"
                    : (inline ? "inlineattach" : "attach");
            boolean editable = isFileEditableInDocEditor(pname);

            sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'"
                    + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize
                    + ",value4:"
                    + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'")
                    + ", editable: " + editable + " },\n";
        }
        if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash()
                && !mcache.isArchive()) {
            if (vheader != null && vheader[0] != null && !wasseen) {
                sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n";
            }
        }

        String h = getSingleHeaderValue(m, "Sonicle-send-scheduled");
        if (h != null && h.equals("true")) {
            java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"),
                    getSingleHeaderValue(m, "Sonicle-send-time"));
            if (scal != null) {
                java.util.Date sd = scal.getTime();
                String sdate = df.format(sd).replaceAll("\\.", ":");
                sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate)
                        + "',value2:'',value3:0},\n";
            }
        }

        if (ir != null) {

            /*
            ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId());
            if (calMgr != null) {
               if (ir.getMethod().equals("REPLY")) {
                  calMgr.updateEventFromICalReply(ir.getCalendar());
                  //TODO: gestire lato client una notifica di avvenuto aggiornamento
               } else {
                  Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID())
                  if (evt != null) {
             UserProfileId pid = getEnv().getProfileId();
             UserProfile.Data ud = WT.getUserData(pid);
             boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress());
             boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId()));
                     
             if (!iAmOrganizer && !iAmOwner) {
                //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request
             }
                  }
               }
            }
            */

            ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true,
                    environment.getProfileId());
            if (cm != null) {
                int eid = -1;
                //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID());
                Event ev = null;
                if (ir.getMethod().equals("REPLY")) {
                    // Previous impl. forced (forceOriginal == true)
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                } else {
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                }

                UserProfileId pid = getEnv().getProfileId();
                UserProfile.Data ud = WT.getUserData(pid);

                if (ev != null) {
                    InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer());
                    boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId()));
                    boolean iAmOrganizer = (organizer != null)
                            && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress());

                    //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde...
                    //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare?

                    if (iAmOwner || iAmOrganizer) {
                        eid = 0;
                        //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp?
                        /*
                        DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC);
                        DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC));
                        if (dtICal.isAfter(dtEvt)) {
                           eid = 0;
                        } else {
                           eid = ev.getEventId();
                        }
                        */
                    }
                }
                sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'"
                        + eid + "'},\n";
            }
        }

        sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date)
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject))
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid)
                + "',value2:'',value3:0}\n";

        if (providername == null && !mcache.isSpecial()) {
            mcache.refreshUnreads();
        }
        long millis = System.currentTimeMillis();
        sout += "\n],\n";

        String svtags = getJSTagsArray(m.getFlags());
        if (svtags != null)
            sout += "tags: " + svtags + ",\n";

        if (isPECView) {
            sout += "pec: true,\n";
        }

        sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n";
        out.println(sout);

        if (im != null)
            im.setPeek(false);

        //            if (!wasopen) folder.close(false);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:net.wastl.webmail.plugins.SendMessage.java

public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head)
        throws WebMailException, ServletException {
    if (sess1 == null) {
        throw new WebMailException(
                "No session was given. If you feel this is incorrect, please contact your system administrator");
    }//from w  ww.j  a va 2 s  . c om
    WebMailSession session = (WebMailSession) sess1;
    UserData user = session.getUser();
    HTMLDocument content;

    Locale locale = user.getPreferredLocale();

    /* Save message in case there is an error */
    session.storeMessage(head);

    if (head.isContentSet("SEND")) {
        /* The form was submitted, now we will send it ... */
        try {
            MimeMessage msg = new MimeMessage(mailsession);

            Address from[] = new Address[1];
            try {
                /**
                 * Why we need
                 * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()?
                 *
                 * Because we specify client browser's encoding to UTF-8, IE seems
                 * to send all data encoded in UTF-8. We have to transcode all byte
                 * sequences we received to UTF-8, and next we encode those strings
                 * using MimeUtility.encodeText() depending on user's locale. Since
                 * MimeUtility.encodeText() is used to convert the strings into its
                 * transmission format, finally we can use the strings in the
                 * outgoing e-mail which relies on receiver's email agent to decode
                 * the strings.
                 *
                 * As described in JavaMail document, MimeUtility.encodeText() conforms
                 * to RFC2047 and as a result, we'll get strings like "=?Big5?B......".
                 */
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
                //                  MimeUtility.encodeText(session.getUser().getFullName()));
                from[0] = new InternetAddress(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale),
                        TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null,
                                locale));
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName());
            }

            StringTokenizer t;
            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("TO").trim(), ",;");
            }

            /* Check To: field, when empty, throw an exception */
            if (t.countTokens() < 1) {
                throw new MessagingException("The recipient field must not be empty!");
            }
            Address to[] = new Address[t.countTokens()];
            int i = 0;
            while (t.hasMoreTokens()) {
                to[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("CC").trim(), ",;");
            }
            Address cc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                cc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("BCC").trim(), ",;");
            }
            Address bcc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                bcc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            session.setSent(false);

            msg.addFrom(from);
            if (to.length > 0) {
                msg.addRecipients(Message.RecipientType.TO, to);
            }
            if (cc.length > 0) {
                msg.addRecipients(Message.RecipientType.CC, cc);
            }
            if (bcc.length > 0) {
                msg.addRecipients(Message.RecipientType.BCC, bcc);
            }
            msg.addHeader("X-Mailer",
                    WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion());

            String subject = null;

            if (!head.isContentSet("SUBJECT")) {
                subject = "no subject";
            } else {
                try {
                    // subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
                    subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1",
                            locale);
                } catch (UnsupportedEncodingException e) {
                    log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                    subject = head.getContent("SUBJECT");
                }
            }

            msg.addHeader("Subject", subject);

            if (head.isContentSet("REPLY-TO")) {
                // msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
                msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"),
                        "ISO8859_1", locale));
            }

            msg.setSentDate(new Date(System.currentTimeMillis()));

            String contnt = head.getContent("BODY");

            //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
            String charset = "utf-8";

            MimeMultipart cont = new MimeMultipart();
            MimeBodyPart txt = new MimeBodyPart();

            // Transcode to UTF-8
            contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8");
            // Encode text
            if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                txt.setText(contnt, "Big5");
                txt.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            } else {
                txt.setText(contnt, "utf-8");
                txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            }

            /* Add an advertisement if the administrator requested to do so */
            cont.addBodyPart(txt);
            if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) {
                MimeBodyPart adv = new MimeBodyPart();
                String file = "";
                if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) {
                    file = store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                } else {
                    file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator")
                            + store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                }
                String advcont = "";
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(file));
                    String line = fin.readLine();
                    while (line != null && !line.equals("")) {
                        advcont += line + "\n";
                        line = fin.readLine();
                    }
                    fin.close();
                } catch (IOException ex) {
                }

                /**
                 * Transcode to UTF-8; Since advcont comes from file, we transcode
                 * it from default encoding.
                 */
                // Encode text
                if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                    advcont = new String(advcont.getBytes(), "Big5");
                    adv.setText(advcont, "Big5");
                    adv.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                } else {
                    advcont = new String(advcont.getBytes(), "UTF-8");
                    adv.setText(advcont, "utf-8");
                    adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                }

                cont.addBodyPart(adv);
            }
            for (String attachmentKey : session.getAttachments().keySet()) {
                ByteStore bs = session.getAttachment(attachmentKey);
                InternetHeaders ih = new InternetHeaders();
                ih.addHeader("Content-Transfer-Encoding", "BASE64");

                PipedInputStream pin = new PipedInputStream();
                PipedOutputStream pout = new PipedOutputStream(pin);

                /* This is used to write to the Pipe asynchronously to avoid blocking */
                StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000);
                BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64"));
                encoder.write(bs.getBytes());
                encoder.flush();
                encoder.close();
                //MimeBodyPart att1=sconn.getResult();
                MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes());

                if (bs.getDescription() != "") {
                    att1.setDescription(bs.getDescription(), "utf-8");
                }
                /**
                 * As described in FileAttacher.java line #95, now we need to
                 * encode the attachment file name.
                 */
                // att1.setFileName(bs.getName());
                String fileName = bs.getName();
                String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry());
                String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null);
                if (encodedFileName.equals(fileName)) {
                    att1.addHeader("Content-Type", bs.getContentType());
                    att1.setFileName(fileName);
                } else {
                    att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset);
                    encodedFileName = encodedFileName.substring(localeCharset.length() + 5,
                            encodedFileName.length() - 2);
                    encodedFileName = encodedFileName.replace('=', '%');
                    att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''"
                            + encodedFileName);
                }
                cont.addBodyPart(att1);
            }
            msg.setContent(cont);
            //              }

            msg.saveChanges();

            boolean savesuccess = true;

            msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid"));
            if (session.getUser().wantsSaveSent()) {
                String folderhash = session.getUser().getSentFolder();
                try {
                    Folder folder = session.getFolder(folderhash);
                    Message[] m = new Message[1];
                    m[0] = msg;
                    folder.appendMessages(m);
                } catch (MessagingException e) {
                    savesuccess = false;
                } catch (NullPointerException e) {
                    // Invalid folder:
                    savesuccess = false;
                }
            }

            boolean sendsuccess = false;

            try {
                Transport.send(msg);
                Address sent[] = new Address[to.length + cc.length + bcc.length];
                int c1 = 0;
                int c2 = 0;
                for (c1 = 0; c1 < to.length; c1++) {
                    sent[c1] = to[c1];
                }
                for (c2 = 0; c2 < cc.length; c2++) {
                    sent[c1 + c2] = cc[c2];
                }
                for (int c3 = 0; c3 < bcc.length; c3++) {
                    sent[c1 + c2 + c3] = bcc[c3];
                }
                sendsuccess = true;
                throw new SendFailedException("success", new Exception("success"), sent, null, null);
            } catch (SendFailedException e) {
                session.handleTransportException(e);
            }

            //session.clearMessage();

            content = new XHTMLDocument(session.getModel(),
                    store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme()));
            //              if(sendsuccess) session.clearWork();
        } catch (Exception e) {
            log.error("Could not send messsage", e);
            throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")");
        }

    } else if (head.isContentSet("ATTACH")) {
        /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
           have two targets without Javascript) */
        content = parent.getURLHandler().handleURL("/compose/attach", session, head);
    } else {
        throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
    }
    return content;
}

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

protected Store connectStore(String host, String protocol, String login, String password)
        throws MessagingException {
    /* Check whether the domain of this user allows to connect to the host */
    WebMailVirtualDomain vdom = parent.getStorage().getVirtualDomain(user.getDomain());
    if (!vdom.isAllowedHost(host)) {
        throw new MessagingException("You are not allowed to connect to this host");
    }/*from   ww w  . j  a  v a2  s  .  c o m*/
    imapBasedir = vdom.getImapBasedir();

    /* Check if this host is already connected. Use connection if true, create a new one if false. */
    Store st = stores.get(host + "-" + protocol);
    if (st == null) {
        st = mailsession.getStore(protocol);
        stores.put(host + "-" + protocol, st);
    }

    /* Maybe this is a new store or this store has been disconnected. Reconnect if this is the case. */
    if (!st.isConnected()) {
        try {
            st.connect(host, login, password);
            log.info("Mail: Connection to " + st.toString() + ".");
        } catch (AuthenticationFailedException ex) {
            /* If login fails, try the login_password */
            if (!login_password.equals(password)
                    && parent.getStorage().getConfig("FOLDER TRY LOGIN PASSWORD").toUpperCase().equals("YES")) {
                st.connect(host, login, login_password);
                log.info("Mail: Connection to " + st.toString()
                        + ", second attempt with login password succeeded.");
            } else {
                throw ex;
            }
        }
    }
    return st;
}

From source file:org.apache.camel.component.mail.MailConsumer.java

protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;//  ww  w.  jav  a 2s . com
    pendingExchanges = 0;
    int polledMessages = 0;

    ensureIsConnected();

    if (store == null || folder == null) {
        throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: "
                + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Polling mailfolder: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (getEndpoint().getConfiguration().getFetchSize() == 0) {
        LOG.warn(
                "Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll.");
        return 0;
    }

    // ensure folder is open
    if (!folder.isOpen()) {
        folder.open(Folder.READ_WRITE);
    }

    try {
        int count = folder.getMessageCount();
        if (count > 0) {
            Message[] messages;

            // should we process all messages or only unseen messages
            if (getEndpoint().getConfiguration().isUnseen()) {
                messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
            } else {
                messages = folder.getMessages();
            }

            polledMessages = processBatch(CastUtils.cast(createExchanges(messages)));
        } else if (count == -1) {
            throw new MessagingException("Folder: " + folder.getFullName() + " is closed");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        // need to ensure we release resources
        try {
            if (folder.isOpen()) {
                folder.close(true);
            }
        } catch (Exception e) {
            // some mail servers will lock the folder so we ignore in this case (CAMEL-1263)
            LOG.debug("Could not close mailbox folder: " + folder.getName(), e);
        }
    }

    return polledMessages;
}

From source file:org.apache.james.core.MimeMessageWrapper.java

/**
 * This is the MimeMessage implementation - this should return ONLY the
 * body, not the entire message (should not count headers). This size will
 * never change on {@link #saveChanges()}
 *//*  w w  w.  j  a v  a 2  s  . co  m*/
@Override
public synchronized int getSize() throws MessagingException {
    if (source != null) {
        try {
            long fullSize = source.getMessageSize();
            if (headers == null) {
                loadHeaders();
            }
            // 2 == CRLF
            return (int) (fullSize - initialHeaderSize - 2);

        } catch (IOException e) {
            throw new MessagingException("Unable to calculate message size");
        }
    } else {
        if (!messageParsed) {
            loadMessage();
        }

        return super.getSize();
    }

}