package es.sinjava.labs; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.InvalidPropertiesFormatException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mailer { Properties props = new Properties(); public Mailer(String destiny, String subject, String text) throws AddressException { this(new InternetAddress(destiny), subject, text); } public Mailer(InternetAddress destiny, String subject, String text) { props = loadConfiguration(); Session session = Session.getDefaultInstance(props); session.setDebug(true); String from = props.getProperty("mail.smtp.user"); MimeMessage message = createMessage(destiny, subject, text, session, from); sendMessage(session, from, message); } private Properties loadConfiguration() { Properties propertiesFromFile = new Properties(); try { propertiesFromFile.loadFromXML(new FileInputStream("mail.xml")); } catch (InvalidPropertiesFormatException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return propertiesFromFile; } private void sendMessage(Session session, String from, MimeMessage message) { Transport t; String pass = props.getProperty("mail.smtp.pass"); try { t = session.getTransport("smtp"); t.connect(from, pass); t.sendMessage(message, message.getAllRecipients()); t.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } private MimeMessage createMessage(InternetAddress destiny, String subject, String text, Session session, String from) { MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, destiny); message.setSubject(subject); message.setText(text); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } return message; } }