Example usage for javax.mail.internet MimeUtility encodeText

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

Introduction

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

Prototype

public static String encodeText(String text, String charset, String encoding)
        throws UnsupportedEncodingException 

Source Link

Document

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

Usage

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

public void sendingHtml(String destinatario, String nome, String assunto, URL linkBoleto) {
    try {/*from w  w w  .  j  ava2 s  .c  om*/

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        URL url = linkBoleto;//new URL(linkBoleto);
        String cid = email.embed(url, new BusinessDelegate().getMensagem(new BigDecimal(61)).getAssunto());

        // localizando a mensagem
        //Mensagem msg = new Mensagem();
        //msg = new BusinessDelegate().getMensagem(mensagemId);

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        body += (this.bodyProfissional);
        body += ("Fa&ccedil;a Download do Boleto para pagamento: - <a href=" + url
                + " target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        body += "<img src=\"cid:" + cid + "\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(null);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SendHtmlFormatedEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);//from  w  w  w . ja va  2 s . c  o  m
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:com.cubusmail.mail.MessageHandler.java

/**
 * @param subject/*from ww w .  j  a va2 s .c o  m*/
 * @throws MessagingException
 */
public void setSubject(String subject) throws MessagingException {

    try {
        this.message.setSubject(MimeUtility.encodeText(subject, this.charset, subjectEncoding), this.charset);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
        this.message.setSubject(subject);
    }
}

From source file:br.com.itfox.beans.SendHtmlFormatedEmail.java

/**
*
* @param destinatario//from  w  w w . ja v a  2s  .  co  m
* @param nome
* @param assunto
* @throws IOException
*/

public void sendingHtml(String destinatario, String nome, String assunto, int tipoId) throws IOException {
    try {

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName("mail.congressotrt15.com.br");
        email.setSmtpPort(587);
        email.setAuthenticator(new DefaultAuthenticator("congresso@congressotrt15.com.br", "admtrt15xx"));
        email.setSSLOnConnect(false);
        //email.setTLS(true);
        email.setFrom("congresso@congressotrt15.com.br");
        //email.setSubject("TestMail");
        email.addTo(destinatario, nome);
        //email.setFrom("belchiorpalma@me.com", "Me");
        email.setSubject(assunto);
        email.setSubject(MimeUtility.encodeText(assunto, "UTF-8", "B"));

        // embed the image and get the content id
        // URL url = linkBoleto;//new URL(linkBoleto);
        //String cid = email.embed(url, "Congresso TRT 15");

        // set the html message
        //email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");
        String body = "";
        body += this.htmlHead;
        if (tipoId == 1) {
            body += (this.bodyProfissional);
        } else if (tipoId == 2) {
            body += (this.bodyServidor);
        } else if (tipoId == 3) {
            body += (this.bodyMagistrado);
        } else if (tipoId == 4) {
            body += (this.bodyEstudante);
        } else {
            body += "Congresso TRT";
        }

        // body+=("Faa Download do Boleto para pagamento: - <a href="+url+" target=\"_blank\">Clique Aqui para baixar o Boleto.</a>");
        //body+="<img src=\"cid:"+cid+"\">";
        body += ("</body></html>");
        //email.setContent(body,CONTENT_TYPE);
        email.setHtmlMsg(body);
        //email.setHeaders(CONTENT_TYPE);
        //email.setHtmlMsg(body);
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException ex) {
        // utils.Logger.getLogger("Erro ao enviar Email. "+tipoId+" - "+ex.toString(),tipoId);
        // utils.Logger.getLoggerPessoaFisica("Erro ao enviar email - sending html:"+ex.getMessage());
    }

}

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;/* w  w w  .  j a  va2 s  .  c o  m*/
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

From source file:com.zimbra.common.util.HttpUtil.java

/**
 * Used to encode filenames to be safe for browser headers
 *
 * Note: Due to browsers finally starting to implement RFC 5987 its better
 * to use the createContentDisposition() method below so it can
 * setup the filename= or filename*= correctly based on the browser
 *
 * @param browser//w  w  w  .ja  va 2s  .  c  o  m
 * @param filename
 * @return
 */
@Deprecated
public static String encodeFilename(Browser browser, String filename) {
    filename = StringUtil.sanitizeFilename(filename);
    if (StringUtil.isAsciiString(filename) && filename.indexOf('"') == -1) {
        return '"' + filename + '"';
    }
    try {
        switch (browser) {
        case IE:
            return new String(URLCodec.encodeUrl(IE_URL_SAFE, filename.getBytes(Charsets.UTF_8)),
                    Charsets.ISO_8859_1);
        case CHROME:
        case SAFARI:
            // Safari doesn't support any encoding. The only solution is
            // to let Safari use the path-info in URL by returning no
            // filename here.
            return "";
        case FIREFOX:
        default:
            return '"' + MimeUtility.encodeText(filename, "utf-8", "B") + '"';
        }
    } catch (UnsupportedEncodingException uee) {
        return filename;
    }
}

From source file:com.ikon.util.WebUtils.java

/**
 * Prepare to send the file./*from   w  w w  .j a va2 s  .  c  o  m*/
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String agent = request.getHeader("USER-AGENT");

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (null != agent && -1 != agent.indexOf("MSIE")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

From source file:com.openkm.util.WebUtils.java

/**
 * Prepare to send the file./*  w  w w  .  j av a 2 s . com*/
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String userAgent = WebUtils.getHeader(request, "user-agent").toLowerCase();

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (userAgent.contains("msie") || userAgent.contains("trident")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
        log.debug("Agent: iPhone - iPad");
        // Do nothing
    } else if (userAgent.contains("android")) {
        log.debug("Agent: Android");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");
    } else if (userAgent.contains("mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: attachment
 *
 * @param file//w w w . j  a v a2  s.c o  m
 *            
 * @return MimeBodyPartContent-Disposition: attachment?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createAttachmentPart(AttachmentFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    attachmentPart.setDataHandler(new DataHandler(file.getDataSource()));
    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
    return attachmentPart;
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: inline
 *
 * @param file/*from   w  ww . ja v a 2s. c  om*/
 *            ?
 * @return MimeBodyPartContent-Disposition: inline?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createImagePart(InlineImageFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart imagePart = new MimeBodyPart();
    imagePart.setContentID(file.getContentId());
    imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    imagePart.setDataHandler(new DataHandler(file.getDataSource()));
    imagePart.setDisposition(MimeBodyPart.INLINE);
    return imagePart;
}