Example usage for javax.mail Message writeTo

List of usage examples for javax.mail Message writeTo

Introduction

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

Prototype

public void writeTo(OutputStream os) throws IOException, MessagingException;

Source Link

Document

Output a bytestream for this Part.

Usage

From source file:Main.java

public static File buildEmlFile(Message message, int i)
        throws MessagingException, FileNotFoundException, IOException {
    File file = new File("e:\\" + i + ".eml");
    //        MimeUtility.decodeText(message.getSubject()).trim()
    message.writeTo(new FileOutputStream(file));
    return file;/*from   www  .  ja  va  2 s  .  c  o  m*/
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;/*from w  w w.j  av  a 2s.com*/
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.apache.axis2.transport.mail.LogAspect.java

@Before("call(void javax.mail.Transport.send(javax.mail.Message)) && args(message)")
public void beforeSend(Message message) {
    try {//w ww  . j  a v a  2 s .  com
        OutputStream out = LogManager.INSTANCE.createLog("javamail");
        try {
            message.writeTo(out);
        } finally {
            out.close();
        }
    } catch (Throwable ex) {
        log.error("Failed to dump mail message", ex);
    }
}

From source file:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java

private void backup(Message message) throws FileNotFoundException, IOException, MessagingException {
    String filename = UUID.randomUUID().toString().concat(".txt");
    message.writeTo(new FileOutputStream(backupPath.concat(filename)));
}

From source file:org.apache.hupa.server.handler.GetRawMessageHandler.java

@Override
protected RawMessageResult executeInternal(RawMessage action, ExecutionContext context) throws ActionException {
    User user = getUser();//from  ww w.jav a2 s  .c o  m
    long uid = action.getUid();
    org.apache.hupa.shared.data.IMAPFolder folder = action.getFolder();
    try {
        IMAPStore store = cache.get(user);
        IMAPFolder f = (IMAPFolder) store.getFolder(folder.getFullName());
        if (f.isOpen() == false) {
            f.open(Folder.READ_ONLY);
        }
        Message m = f.getMessageByUID(action.getUid());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        m.writeTo(out);
        if (f.isOpen()) {
            f.close(false);
        }
        return new RawMessageResult(out.toString());
    } catch (Exception e) {
        logger.error("Unable to get raw content of msg for user " + user + " in folder " + folder + " with uid "
                + uid, e);
        throw new ActionException("Unable to et raw content of msg for user " + user + " in folder " + folder
                + " with uid " + uid);
    }

}

From source file:org.apache.james.mailets.utils.SMTPMessageSender.java

private String asString(Message message) throws IOException, MessagingException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    message.writeTo(outputStream);
    return new String(outputStream.toByteArray(), Charsets.UTF_8);
}

From source file:com.linuxbox.enkive.importer.AbstractMessageImporter.java

protected void sendMessage(Message m) throws IOException, MessagingException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    m.writeTo(os);
    os.close();//from   w  w  w . j a va  2 s . c om
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(os.toByteArray())));
    sendMessage(reader);
    reader.close();
    os.reset();
}

From source file:org.apache.hupa.server.servlet.MessageSourceServlet.java

/**
 * Handle to write back the requested attachment
 *///from   www  .jav a 2 s  . c o m
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    OutputStream outs = null;
    try {
        long uid = Long.parseLong(message_uuid);

        IMAPStore store = cache.get(user);
        IMAPFolder f = (IMAPFolder) store.getFolder(folderName);
        if (f.isOpen() == false) {
            f.open(Folder.READ_ONLY);
        }

        Message m = f.getMessageByUID(uid);

        response.setContentType("text/plain");
        outs = response.getOutputStream();
        m.writeTo(outs);
        outs.flush();

        if (f.isOpen()) {
            f.close(false);
        }
    } catch (Exception e) {
        String msg = "Unable to get raw content of msg for user " + user + " in folder " + folderName
                + " with uid " + message_uuid;
        logger.error(msg, e);
        throw new ServletException(msg, e);
    } finally {
        IOUtils.closeQuietly(outs);
    }
}

From source file:org.apache.james.utils.SMTPMessageSender.java

private String asString(Message message) throws IOException, MessagingException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    message.writeTo(outputStream);
    return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
}

From source file:org.xwiki.contrib.mailarchive.script.internal.MailArchiveScriptService.java

@Override
public String getOriginal(String serverId, String messageId) {
    String original = null;/*from  w  ww .  j a v  a  2  s.c  om*/

    try {
        Message message = this.mailArchive.getFromStore(serverId, messageId);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);
        // FIXME: not sure about utf-8 here...
        original = baos.toString("UTF-8");
    } catch (Exception e) {
        logger.debug("Error retrieving original message", e);
    }

    return original;
}