private void sendMail(String from, String recipient, String subject, String message , File[] files)
throws MessagingException {
Session session = null;
props = new Properties();
props.put( "mail.smtp.host", Settings.getInstance().getValue("mail.smtp.host") );
// wenn eine Authentifizierung erforderlich ist
if( Settings.getInstance().getValue("mail.smtp.auth.required").equals("1") ) {
System.out.println("Authentifcation activated");
session = Session.getInstance( props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String usr = Settings.getInstance().getValue("mail.smtp.auth.user");
String pwd = Settings.getInstance().getValue("mail.smtp.auth.password");
System.out.println("Auth with user: " + usr);
return new PasswordAuthentication(usr, pwd);
}
});
} else {
System.out.println("Authentifcation deactivated");
session = Session.getDefaultInstance( props );
}
MimeMultipart mimeMultipart = new MimeMultipart();
InternetAddress addressFrom = new InternetAddress( from );
InternetAddress addressTo = new InternetAddress( recipient );
Message msg = new MimeMessage( session );
msg.setFrom( addressFrom );
msg.setRecipient( MimeMessage.RecipientType.TO, addressTo );
msg.setSubject( subject );
MimeBodyPart text = new MimeBodyPart();
text.setText(message);
text.setDisposition(MimeBodyPart.INLINE);
// Mail-Anhänge
for(File file2send : files) {
MimeBodyPart attachement = new MimeBodyPart();
if(file2send != null && file2send.exists() && file2send.canRead()) {
attachement.setDataHandler(new DataHandler(new FileDataSource(file2send)));
attachement.setFileName(file2send.getName());
attachement.setDisposition(MimeBodyPart.ATTACHMENT);
// an EMail anhängen
mimeMultipart.addBodyPart(attachement);
}
}
mimeMultipart.addBodyPart(text);
msg.setContent(mimeMultipart);
// EMail versenden
Transport.send( msg );
}