public void sendMailWithAttachment ( String to , String subject , String content , String filename ) throws MessagingException { Properties props = new Properties ( ) ; props . put ( "mail.smtp.user" , emailConfg . getUser ( ) ) ; props . put ( "mail.smtp.host" , emailConfg . getHost ( ) ) ; props . put ( "mail.smtp.port" , emailConfg . getPort ( ) ) ; props . put ( "mail.smtp.starttls.enable" , "true" ) ; props . put ( "mail.smtp.debug" , emailConfg . getDebug ( ) ) ; props . put ( "mail.smtp.auth" , emailConfg . getAuth ( ) ) ; props . put ( "mail.smtp.ssl.trust" , emailConfg . host ) ; SMTPAuthenticator auth = new SMTPAuthenticator ( emailConfg . getUser ( ) , ( String ) secret . get ( SecretConstants . EMAIL_PASSWORD ) ) ; Session session = Session . getInstance ( props , auth ) ; MimeMessage message = new MimeMessage ( session ) ; message . setFrom ( new InternetAddress ( emailConfg . getUser ( ) ) ) ; message . addRecipient ( Message . RecipientType . TO , new InternetAddress ( to ) ) ; message . setSubject ( subject ) ; // Create the message part BodyPart messageBodyPart = new MimeBodyPart ( ) ; // Now set the actual message messageBodyPart . setText ( content ) ; // Create a multipar message Multipart multipart = new MimeMultipart ( ) ; // Set text message part multipart . addBodyPart ( messageBodyPart ) ; // Part two is attachment messageBodyPart = new MimeBodyPart ( ) ; DataSource source = new FileDataSource ( filename ) ; messageBodyPart . setDataHandler ( new DataHandler ( source ) ) ; messageBodyPart . setFileName ( filename ) ; multipart . addBodyPart ( messageBodyPart ) ; // Send the complete message parts message . setContent ( multipart ) ; // Send message Transport . send ( message ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "An email has been sent to " + to + " with subject " + subject ) ; }
Send email with a string content and attachment