public static MimeMessage createMimeMessage ( Session session , String from , String [ ] to , String subject , String content , DataSource [ ] attachments ) { logger . debug ( "Creates a mime message with {} attachments" , ( attachments == null ) ? 0 : attachments . length ) ; try { MimeMessage message = new MimeMessage ( session ) ; if ( from != null ) { message . setSender ( new InternetAddress ( from ) ) ; } if ( subject != null ) { message . setSubject ( subject , "UTF-8" ) ; } if ( to != null ) { for ( String toAdr : to ) { message . addRecipient ( Message . RecipientType . TO , new InternetAddress ( toAdr ) ) ; } } if ( attachments == null || attachments . length == 0 ) { // Setup a plain text message message . setContent ( content , "text/plain; charset=UTF-8" ) ; } else { // Setup a multipart message Multipart multipart = new MimeMultipart ( ) ; message . setContent ( multipart ) ; // Create the message part BodyPart messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setContent ( content , "text/plain; charset=UTF-8" ) ; multipart . addBodyPart ( messageBodyPart ) ; // Add attachments, if any if ( attachments != null ) { for ( DataSource attachment : attachments ) { BodyPart attatchmentBodyPart = new MimeBodyPart ( ) ; attatchmentBodyPart . setDataHandler ( new DataHandler ( attachment ) ) ; attatchmentBodyPart . setFileName ( attachment . getName ( ) ) ; multipart . addBodyPart ( attatchmentBodyPart ) ; } } } return message ; } catch ( AddressException e ) { throw new RuntimeException ( e ) ; } catch ( MessagingException e ) { throw new RuntimeException ( e ) ; } }
Creates a mime - message multipart if attachements are supplied otherwise as plain text . Assumes UTF - 8 encoding for both subject and content .