Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package es.sinjava.labs;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- 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 text) {
- props = loadConfiguration();
- InternetAddress destiny = getDestinyFromProperties(props);
- Session session = Session.getDefaultInstance(props);
- session.setDebug(true);
- String from = props.getProperty("mail.smtp.user");
- SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
- String subject = "PortalMessage " + sdf.format((new Date()));
- MimeMessage message = createMessage(destiny, subject, text, session,
- from);
- sendMessage(session, from, message);
- }
- private InternetAddress getDestinyFromProperties(Properties props2) {
- String destinyString = props.getProperty("info");
- InternetAddress destiny = null;
- try {
- destiny = new InternetAddress(destinyString);
- } catch (AddressException e) {
- e.printStackTrace();
- }
- return destiny;
- }
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement