Generating Attachments At Runtime/Add IO Streams in Java Mail

I’ve recently come across a requirement where i had to create some reports at runtime while sending the mail in Java. I expect Every One to have prior knowledge of how to send a mail in java else you go through my previous post

Lets take an example where we have set of encrypted reports in a directory so that none who is having access to system be able to open the report. And We want to decrypt an encrypted report while sending a mail ( As our system is authorized/ or knows the process of decrypting it).

Here is how we perform such an operation using Java Mail.

Java Mail Uses Activation Framework which Contains a Class called  javax.activation.FileDataSource.

All we need to do is to Extend this class and Override its getInputStream() Method. Here is How it is done

    /*
     * (non-Javadoc)
     * 
     * @see javax.activation.FileDataSource#getInputStream()
     */
    public InputStream getInputStream() throws IOException {
        File fileInvoice = new File(strInvoice);
        if (!fileInvoice.exists()) {
            try {
                throw new Exception("File " + encryptedFileName
                        + " does not exist");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // Output file
        OutputStream os = null;
        byte[] bytes = null;

        try {
            os = new ByteArrayOutputStream();
            RSACryptographer rsaCryptoGrapher = new RSACryptographer();
            bytes = rsaCryptoGrapher.crypt(fileInvoice, Cipher.DECRYPT_MODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(bytes);
    }

The above code snippet give you an overview of how to create/modify some document at runtime while sending mail from java. Now here is how we attach this DataSource To Message

messageBodyPart = new MimeBodyPart();
DataSource source = new EncryptedDocumentDataSource(directoryName,encryptedFileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(encrypted);
multipart.addBodyPart(messageBodyPart);

Advertisements

One thought on “Generating Attachments At Runtime/Add IO Streams in Java Mail

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s