Example usage for javax.mail.internet MimeUtility encodeWord

List of usage examples for javax.mail.internet MimeUtility encodeWord

Introduction

In this page you can find the example usage for javax.mail.internet MimeUtility encodeWord.

Prototype

public static String encodeWord(String word, String charset, String encoding)
        throws UnsupportedEncodingException 

Source Link

Document

Encode a RFC 822 "word" token into mail-safe form as per RFC 2047.

Usage

From source file:immf.Util.java

public static void setFileName(Part part, String filename, String charset, String lang)
        throws MessagingException {

    ContentDisposition disposition;/* ww  w  . j ava2  s  .  co  m*/
    String[] strings = part.getHeader("Content-Disposition");
    if (strings == null || strings.length < 1) {
        disposition = new ContentDisposition(Part.ATTACHMENT);
    } else {
        disposition = new ContentDisposition(strings[0]);
        disposition.getParameterList().remove("filename");
    }

    part.setHeader("Content-Disposition",
            disposition.toString() + encodeParameter("filename", filename, charset, lang));

    ContentType cType;
    strings = part.getHeader("Content-Type");
    if (strings == null || strings.length < 1) {
        cType = new ContentType(part.getDataHandler().getContentType());
    } else {
        cType = new ContentType(strings[0]);
    }

    try {
        // I want to public the MimeUtility#doEncode()!!!
        String mimeString = MimeUtility.encodeWord(filename, charset, "B");
        // cut <CRLF>...
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = mimeString.indexOf('\r')) != -1) {
            sb.append(mimeString.substring(0, i));
            mimeString = mimeString.substring(i + 2);
        }
        sb.append(mimeString);

        cType.setParameter("name", new String(sb));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("Encoding error", e);
    }
    part.setHeader("Content-Type", cType.toString());
}

From source file:org.chimi.s4s.controller.FileDownloadController.java

private String getHeaderFileName(String fileName, HttpServletRequest request)
        throws UnsupportedEncodingException {
    String userAgent = request.getHeader("User-Agent");
    boolean ie = userAgent != null && userAgent.indexOf("MSIE") > -1;
    if (ie) {/*  w  w w .  j a v  a  2  s  .  co m*/
        return URLEncoder.encode(fileName, "UTF-8");
    }
    return MimeUtility.encodeWord(fileName, "UTF-8", "B");
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutputs(ReportExecutionJob job, MimeMessageHelper messageHelper, List reportOutputs)
        throws MessagingException, JobExecutionException {
    String attachmentName = null;
    DataContainer attachmentData = job.createDataContainer();
    boolean close = true;
    ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
    try {//from www  . ja va2 s .  co  m
        for (Iterator it = reportOutputs.iterator(); it.hasNext();) {
            ReportOutput output = (ReportOutput) it.next();
            if (attachmentName == null)
                attachmentName = removeExtension(output.getFilename()) + ".zip";
            zipOutput(job, output, zipOut);
        }
        zipOut.finish();
        zipOut.flush();
        close = false;
        zipOut.close();
    } catch (IOException e) {
        throw new JSExceptionWrapper(e);
    } finally {
        if (close) {
            try {
                zipOut.close();
            } catch (IOException e) {
                log.error("Error closing stream", e);
            }
        }
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output,
        boolean useZipFormat) throws MessagingException, JobExecutionException {
    String attachmentName;/*  w w  w  .  j  a v a  2 s  .c om*/
    DataContainer attachmentData;
    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else if (useZipFormat) { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOutput(job, output, zipOut);
            zipOut.finish();
            zipOut.flush();
            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }

        attachmentName = output.getFilename() + ".zip";
    } else { // NO ZIP FORMAT
        attachmentName = output.getFilename();
        try {
            attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
        } catch (UnsupportedEncodingException e) {
            throw new JSExceptionWrapper(e);
        }
        StringBuffer primaryPage = null;
        for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
            ReportOutput child = (ReportOutput) it.next();
            String childName = child.getFilename();

            // NOTE:  add the ".dat" extension to all image resources
            // email client will automatically append ".dat" extension to all the files with no extension
            // should do it in JasperReport side
            if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
                if (primaryPage == null)
                    primaryPage = new StringBuffer(new String(output.getData().getData()));
                int fromIndex = 0;
                while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                    primaryPage.insert(fromIndex + 5 + childName.length(), ".dat");
                }
                childName = childName + ".dat";
            }

            try {
                childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null);
            } catch (UnsupportedEncodingException e) {
                throw new JSExceptionWrapper(e);
            }
            messageHelper.addAttachment(childName, new DataContainerResource(child.getData()));
        }
        if (primaryPage == null) {
            messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData()));
        } else {
            messageHelper.addAttachment(attachmentName,
                    new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes())));
        }
        return;
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:immf.Util.java

public static String encodeGoomojiSubject(String subject) throws UnsupportedEncodingException {
    final int maxlen = 75 - ("=?UTF-8?B?".length() + "?=".length());
    StringBuilder sb = new StringBuilder();

    int mark = 0;
    int utf8len = "X-Goomoji-Subject: ".length();
    for (int i = 0; i < subject.length();) {
        int cp = subject.codePointAt(i);
        int len;//w w w .  ja  v a2s  . c o  m
        if (cp < 0x7f)
            len = 1;
        else if (cp <= 0x7ff)
            len = 2;
        else if (cp <= 0xffff)
            len = 3;
        else
            len = 4;

        if (4 * ((utf8len + len - 1) / 3 + 1) >= maxlen) {
            if (mark > 0)
                sb.append("\r\n ");
            sb.append(MimeUtility.encodeWord(subject.substring(mark, i), "UTF-8", "B"));
            mark = i;
            utf8len = 0;
        }

        utf8len += len;
        i += Character.charCount(cp);
    }
    if (mark > 0)
        sb.append("\r\n ");
    sb.append(MimeUtility.encodeWord(subject.substring(mark), "UTF-8", "B"));

    return sb.toString();
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

/**
 * ???User-Agent???????.//from   w ww  .  ja  v a 2s  .  com
 * <ul>
 * <li>IE????????????</li>
 * <li>User-Agent??????</li>
 * <li>?????256????????????????????</li>
 * </ul>
 * @param request 
 * @param response ?
 * @param fileName ???
 */
private void setHeaderFileName(HttpServletRequest request, HttpServletResponse response, String fileName,
        boolean downloadByRealFileName) {
    String headerFileName;
    String userAgent = request.getHeader("User-Agent");
    try {
        if (userAgent.indexOf("MSIE") != -1) {
            //  IE??????????
            String enc = SystemConfig.getValue(KEY_DOWNLOAD_HEADER_FILENAME_ENCODING);
            headerFileName = new String(fileName.getBytes(enc), "iso-8859-1");
            //  ???????
            //  URL????? + ????256byte????????
            //  ???
            //                headerFileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            //  ???????MIME????
            //  see RFC2231
            headerFileName = MimeUtility.encodeWord(fileName, "ISO-2022-JP", "B");
        }
        //  SpreadsheetMLExcel 2007??????????
        //  *.xml?
        if (!downloadByRealFileName && headerFileName.endsWith(".xls")) {
            headerFileName = headerFileName.replaceAll("\\.xls$", ".xml");
        }
        response.addHeader("Content-Disposition", "attachment; filename=\"" + headerFileName + "\"");
    } catch (UnsupportedEncodingException ignore) {
        log.warn(String.format("failed to set filename to response header. %s", fileName), ignore);
    }
}

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

/**
 * A better version of setFileName() which will encode the name if
 * necessary. Why doesn't JAVA Mail do this?
 *
 * @param part the part to manipulate/*from  w  w w.ja v a2  s .c o m*/
 * @param name the give file name encoded in UTF (JAVA)
 * @param charset the encoding character set
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void setFileName(Part part, String name, String charset) throws MessagingException {
    try {
        name = MimeUtility.encodeWord(name, charset, null);
    } catch (Exception xex) {
    }

    part.setFileName(name);
}

From source file:org.openbravo.client.application.report.BaseReportActionHandler.java

/**
 * Downloads the file with the report result. The file is stored in a temporary folder with a
 * generated name. It is renamed and download as an attachment of the response. Once it is
 * finished the file is removed from the server.
 *///from   w  w  w .  ja  v  a 2s.  c  o m
private void doDownload(HttpServletRequest request, Map<String, Object> parameters) throws IOException {
    final String strFileName = (String) parameters.get("fileName");
    final String tmpFileName = (String) parameters.get("tmpfileName");
    ExportType expType = null;

    if (strFileName.endsWith("." + ExportType.PDF.getExtension())) {
        expType = ExportType.PDF;
    } else if (strFileName.endsWith("." + ExportType.XLS.getExtension())) {
        expType = ExportType.XLS;
    } else {
        throw new IllegalArgumentException(
                "Trying to download report file with unsupported type " + strFileName);
    }

    if (!expType.isValidTemporaryFileName(tmpFileName)) {
        throw new IllegalArgumentException("Trying to download report with invalid name " + strFileName);
    }

    final String tmpDirectory = ReportingUtils.getTempFolder();
    final File file = new File(tmpDirectory, tmpFileName);
    FileUtility fileUtil = new FileUtility(tmpDirectory, tmpFileName, false, true);
    try {
        final HttpServletResponse response = RequestContext.get().getResponse();

        response.setHeader("Content-Type", expType.getContentType());
        response.setContentType(expType.getContentType());
        response.setCharacterEncoding("UTF-8");
        // TODO: Compatibility code with IE8. To be reviewed when its support is stopped.
        // see issue #29109
        String userAgent = request.getHeader("user-agent");
        if (userAgent.contains("MSIE")) {
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(strFileName, "utf-8") + "\"");
        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + MimeUtility.encodeWord(strFileName, "utf-8", "Q") + "\"");
        }

        fileUtil.dumpFile(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } finally {
        if (file.exists()) {
            file.delete();
        }
    }
}

From source file:org.openbravo.erpCommon.businessUtility.TabAttachments.java

private void printPageFile(HttpServletResponse response, VariablesSecureApp vars, String strFileReference,
        HttpServletRequest request) throws IOException, ServletException {
    String fileDir = null;// w  ww.  ja v  a  2 s .co  m
    final TabAttachmentsData[] data = TabAttachmentsData.selectEdit(this, strFileReference);

    // Checks if the user has readable access to the record where the file is attached
    Entity entity = ModelProvider.getInstance().getEntityByTableId(data[0].adTableId);
    if (entity != null) {
        Object object = OBDal.getInstance().get(entity.getMappingClass(), data[0].adRecordId);
        if (object instanceof OrganizationEnabled) {
            SecurityChecker.getInstance().checkReadableAccess((OrganizationEnabled) object);
        }
    }

    if (data == null || data.length == 0)
        throw new ServletException("Missing file");
    FileUtility f = new FileUtility();
    fileDir = getAttachmentDirectory(data[0].adTableId, data[0].adRecordId, data[0].name);
    // FIXME: Get the directory separator from Java runtime
    final File file = new File(globalParameters.strFTPDirectory + "/" + fileDir, data[0].name);
    if (file.exists())
        f = new FileUtility(globalParameters.strFTPDirectory + "/" + fileDir, data[0].name, false, true);
    else
        f = new FileUtility(globalParameters.strFTPDirectory, strFileReference, false, true);
    if (data[0].datatypeContent.equals(""))
        response.setContentType("application/txt");
    else
        response.setContentType(data[0].datatypeContent);
    response.setCharacterEncoding("UTF-8");
    String userAgent = request.getHeader("user-agent");
    if (userAgent.contains("MSIE")) {
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + URLEncoder.encode(data[0].name.replace("\"", "\\\""), "utf-8") + "\"");
    } else {
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + MimeUtility.encodeWord(data[0].name.replace("\"", "\\\""), "utf-8", "Q") + "\"");
    }

    f.dumpFile(response.getOutputStream());
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }//from w  w w . j  ava 2 s .  c om
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}