Example usage for javax.mail.internet InternetHeaders InternetHeaders

List of usage examples for javax.mail.internet InternetHeaders InternetHeaders

Introduction

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

Prototype

public InternetHeaders() 

Source Link

Document

Create an empty InternetHeaders object.

Usage

From source file:com.adaptris.mail.MailSenderImp.java

private void addEmailBody(MimeMultipart multipart) throws MailException {
    try {/*from   w  w w.  ja  v a  2  s. c o m*/
        if (emailBody != null) {
            MimeBodyPart part = create(emailBody, new InternetHeaders(), encoding);
            part.setHeader(Mail.CONTENT_TYPE, bodyContentType);
            multipart.addBodyPart(part);
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
}

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

public static InternetHeaders getHeadersWithFrom(Message message) throws MessagingException {
    Header xheader;//from  ww  w . ja  v  a 2s. com
    InternetHeaders xheaders = new InternetHeaders();
    Enumeration xe = message.getAllHeaders();

    for (; xe.hasMoreElements();) {
        xheader = (Header) xe.nextElement();
        xheaders.addHeader(xheader.getName(), xheader.getValue());
    }

    return xheaders;
}

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

/**
 * DOCUMENT ME!/*  ww w .j  a v  a  2s . c om*/
 *
 * @param message DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static InternetHeaders getHeaders(Message message) throws MessagingException {
    Header xheader;
    InternetHeaders xheaders = new InternetHeaders();
    Enumeration xe = message.getAllHeaders();

    for (; xe.hasMoreElements();) {
        xheader = (Header) xe.nextElement();

        if (!xheader.getName().startsWith("From ")) {
            xheaders.addHeader(xheader.getName(), xheader.getValue());
        }
    }

    return xheaders;
}

From source file:es.pode.administracion.presentacion.noticias.crear.CrearControllerImpl.java

public String tratamientoImagen(FormFile imagenFile) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Realizamos el tratamiento de la imagen [" + imagenFile + "]");
    ImagenVO imagen = new ImagenVO();
    InternetHeaders ih = new InternetHeaders();
    MimeBodyPart mbp = new MimeBodyPart(ih, imagenFile.getFileData());

    DataSource source = new MimePartDataSource(mbp);
    DataHandler dImagen = new DataHandler(source);

    imagen.setDatos(dImagen);/*from w  w w.  jav a  2 s. com*/
    imagen.setNombre(imagenFile.getFileName());
    imagen.setMimeType(imagenFile.getContentType());
    String sUrlImagen = this.getSrvNoticiasService().almacenarImagenNoticia(imagen);
    return sUrlImagen;
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

void createMultiPartFormContent(MockHttpServletRequest request, String contentDisposition, String contentType,
        byte[] content) throws Exception {
    MimeMultipart body = new MimeMultipart();
    request.setContentType(body.getContentType());
    InternetHeaders headers = new InternetHeaders();
    headers.setHeader("Content-Disposition", contentDisposition);
    headers.setHeader("Content-Type", contentType);
    body.addBodyPart(new MimeBodyPart(headers, content));

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    body.writeTo(bout);//from  w  w w.jav  a  2s. c o  m
    request.setContent(bout.toByteArray());
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

MimeMultipart appendMultiPartFormContent(MimeMultipart body, String contentDisposition, String contentType,
        byte[] content) throws Exception {
    InternetHeaders headers = new InternetHeaders();
    headers.setHeader("Content-Disposition", contentDisposition);
    headers.setHeader("Content-Type", contentType);
    body.addBodyPart(new MimeBodyPart(headers, content));

    return body;//from   w w w . j av a  2s  .  c om
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public String submitImportar(ActionMapping mapping, SubmitImportarForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String accion = form.getAccion();
    String resAction = "";
    ResourceBundle datosResources = I18n.getInstance().getResource("application-resources",
            (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE));
    if (datosResources.getString("catalogadorBasico.importar.aceptar").equals(accion)) {
        resAction = "Aceptar";

        if (form.getFichero() == null || form.getFichero().getFileName().equals(""))
            throw new ValidatorException("{catalogadorBasico.importar.error.ficherovacio}");

        //crear el datahandler
        InternetHeaders ih = new InternetHeaders();
        MimeBodyPart mbp = null;/*from   ww  w.j a v  a2s. co m*/
        DataSource source = null;
        DataHandler dh = null;
        try {
            FormFile ff = (FormFile) form.getFichero();
            mbp = new MimeBodyPart(ih, ff.getFileData());
            source = new MimePartDataSource(mbp);
            dh = new DataHandler(source);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al crear el datahandler");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error}");
        }

        //validar el fichero
        Boolean valido = new Boolean(false);
        try {
            valido = this.getSrvValidadorService().obtenerValidacionLomes(dh);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("error al llamar al servicio de validacin");
            }
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");
        }

        if (!valido.booleanValue())
            throw new ValidatorException("{catalogadorBasico.importar.error.novalido}");

        //agregar el datahandler a sesion
        this.getCatalogadorBSession(request).setLomesImportado(dh);

    } else if (datosResources.getString("catalogadorBasico.importar.cancelar").equals(accion)) {
        resAction = "Cancelar";
    }

    return resAction;

}

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 w  w . j  a va  2 s.c o  m
    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:org.apache.axis2.datasource.jaxb.JAXBAttachmentMarshaller.java

public String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String namespace,
        String localPart) {/*w ww  . j  a v a  2s  .c o  m*/

    if (offset != 0 || length != data.length) {
        int len = length - offset;
        byte[] newData = new byte[len];
        System.arraycopy(data, offset, newData, 0, len);
        data = newData;
    }

    if (mimeType == null || mimeType.length() == 0) {
        mimeType = APPLICATION_OCTET;
    }

    if (log.isDebugEnabled()) {
        log.debug("Adding MTOM/XOP byte array attachment for element: " + "{" + namespace + "}" + localPart);
    }

    String cid = null;

    try {
        // Create MIME Body Part
        final InternetHeaders ih = new InternetHeaders();
        final byte[] dataArray = data;
        ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeType);
        final MimeBodyPart mbp = (MimeBodyPart) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return new MimeBodyPart(ih, dataArray);
                } catch (MessagingException e) {
                    throw new OMException(e);
                }
            }
        });

        //Create a data source for the MIME Body Part
        MimePartDataSource mpds = (MimePartDataSource) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new MimePartDataSource(mbp);
            }
        });
        long dataLength = data.length;
        Integer value = null;
        if (msgContext != null) {
            value = (Integer) msgContext.getProperty(Constants.Configuration.MTOM_THRESHOLD);
        } else if (log.isDebugEnabled()) {
            log.debug(
                    "The msgContext is null so the MTOM threshold value can not be determined; it will default to 0.");
        }

        int optimizedThreshold = (value != null) ? value.intValue() : 0;

        if (optimizedThreshold == 0 || dataLength > optimizedThreshold) {
            DataHandler dataHandler = new DataHandler(mpds);
            cid = addDataHandler(dataHandler, false);
        }

        // Add the content id to the mime body part
        mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
    } catch (MessagingException e) {
        throw new OMException(e);
    }

    return cid == null ? null : "cid:" + cid;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java

private static DataHandler createDataHandler(Object value, Class cls, String[] mimeTypes, String cid) {
    if (log.isDebugEnabled()) {
        System.out.println("Construct data handler for " + cls + " cid=" + cid);
    }/*from w  ww  .j a  va2 s  .  c  o m*/
    DataHandler dh = null;
    if (cls.isAssignableFrom(DataHandler.class)) {
        dh = (DataHandler) value;
        if (dh == null) {
            return dh; //return if DataHandler is null
        }

        try {
            Object content = dh.getContent();
            // If the content is a Source, convert to a String due to 
            // problems with the DataContentHandler
            if (content instanceof Source) {
                if (log.isDebugEnabled()) {
                    System.out
                            .println("Converting DataHandler Source content to " + "DataHandlerString content");
                }
                byte[] bytes = (byte[]) ConvertUtils.convert(content, byte[].class);
                String newContent = new String(bytes);
                return new DataHandler(newContent, mimeTypes[0]);
            }
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    } else {
        try {
            byte[] bytes = createBytes(value, cls, mimeTypes);
            // Create MIME Body Part
            InternetHeaders ih = new InternetHeaders();
            ih.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, mimeTypes[0]);
            MimeBodyPart mbp = new MimeBodyPart(ih, bytes);

            //Create a data source for the MIME Body Part
            MimePartDataSource ds = new MimePartDataSource(mbp);

            dh = new DataHandler(ds);
            mbp.setHeader(HTTPConstants.HEADER_CONTENT_ID, cid);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }
    return dh;
}