• In-Memory Attachment via MIME

    By Michael Zischeck 1 decade ago


    I found that to attach file in-memory is quite easy using MIME.

    The thing is when you have an application which should attach files on the server from another source you can use MIME if you do not have the file as a file but rather as an array of bytes ready:

    here some sample code (where here the file is available on C drive, normally I would get it via FTP/WS or another Notes Document)

    // creating the output stream used to create the MIME attachments

    Stream outStream = session.createStream();


    // create the MIME body

    MIMEEntity body = docCurrent.createMIMEEntity();

    String files[] = new String[4];

    files[0] = "c:\temp\1.jpg";

    files[1] = "c:\temp\2.pdf";

    files[2] = "c:\temp\3.doc";

    files[3] = "c:\temp\4.xls";

    // Get the input file

    for( int i = 0; i < files.length; i++) {

    // creating the stream to read the files this is the INPUT stream<br/>
    Stream inStream = session.createStream();<br/>
    inStream.open(files[i], &quot;binary&quot;);<br/>
    // reading the stream into the OUTPUT stream<br/>
    do {<br/>
        byte[] buffer = inStream.read(32767);<br/>
    } while (!inStream.isEOS());<br/>

    // create a child for each attachment<br/>
    MIMEEntity child = body.createChildEntity();<br/>
    // find the fileSuffix<br/>
    String fileSuffix = files[i].substring(files[i].lastIndexOf(&quot;.&quot;)+1);<br/>

    // set the child to the outstream using a mapped MIME type<br/>

    // MIME type mapping see: http://www.w3schools.com/media/media_mimeref.asp

    child.setContentFromBytes(outStream, mapMIMEType(fileSuffix), MIMEEntity.ENC_IDENTITY_BINARY);<br/>
    // set name for file attachment<br/>
    MIMEHeader header = child.createHeader(&quot;Content-Disposition&quot;);<br/>
    header.setHeaderVal(&quot;attachment; filename=\&quot;&quot; + files[i] + &quot;\&quot;&quot;);<br/>
    // set unique id for file attachment to be able to refer to it<br/>
    header = child.createHeader(&quot;Content-ID&quot;);<br/>



    docCurrent.save( true, true );

    Hope someone likes this. It helped me in a very important project where we would use a WS to deliver a fileattachment which needed being attached on the server ( where we do no t have write access) to a document.