public static MimeMultipart createMultipartWithAttachment ( String msg , final byte [ ] attachment , final String contentType , final String filename , String description ) { try { MimeMultipart multiPart = new MimeMultipart ( ) ; MimeBodyPart textPart = new MimeBodyPart ( ) ; multiPart . addBodyPart ( textPart ) ; textPart . setText ( msg ) ; MimeBodyPart binaryPart = new MimeBodyPart ( ) ; multiPart . addBodyPart ( binaryPart ) ; DataSource ds = new DataSource ( ) { @ Override public InputStream getInputStream ( ) throws IOException { return new ByteArrayInputStream ( attachment ) ; } @ Override public OutputStream getOutputStream ( ) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; byteStream . write ( attachment ) ; return byteStream ; } @ Override public String getContentType ( ) { return contentType ; } @ Override public String getName ( ) { return filename ; } } ; binaryPart . setDataHandler ( new DataHandler ( ds ) ) ; binaryPart . setFileName ( filename ) ; binaryPart . setDescription ( description ) ; return multiPart ; } catch ( MessagingException e ) { throw new IllegalArgumentException ( "Can not create multipart message with attachment" , e ) ; } }
Create new multipart with a text part and an attachment