Package de.chris_soft.fyllgen.utilities

Source Code of de.chris_soft.fyllgen.utilities.MailTools

/**
* FyLLGen - A Java based tool for collecting and distributing family data
*
* Copyright (C) 2007-2011 Christian Packenius
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package de.chris_soft.fyllgen.utilities;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
* Pers�nliche Klasse zum Versenden und Empfangen von E-Mails. Wenn die Meldung
* "553 sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)"
* kommt, dann stimmt wohl was mit dem Authenticator nicht.
* @author Christian Packenius, 20100702.
*/
public class MailTools extends Authenticator {
  /**
   * Login-Name des Absenders (f�r POP 3).
   */
  private String login;

  /**
   * Passwort zum Login (f�r POP 3).
   */
  private String password;

  /**
   * Host zum Versand der Mails.
   */
  private String smtpHost;

  /**
   * Port f�r SMTP.
   */
  private int smtpPort;

  /**
   * Host zum Empfang der Mails oder zur Authentifizierung w�hrend des
   * Versendens.
   */
  private String pop3Host;

  /**
   * Mailadresse des Absenders.
   */
  private String from;

  /**
   * Liste aller "normalen" Empf�nger.
   */
  private Vector<String> to = new Vector<String>();

  /**
   * Liste aller Kopie-Empf�nger.
   */
  private Vector<String> cc = new Vector<String>();

  /**
   * Liste aller Blindkopie-Empf�nger.
   */
  private Vector<String> bcc = new Vector<String>();

  /**
   * Attachments.
   */
  private Vector<Object> att = new Vector<Object>();

  /**
   * �berschrift der Mail.
   */
  private String subject;

  /**
   * Inhalt der Mail als Text.
   */
  private String text;

  /**
   * Statische Methode zum Versenden einer E-Mail mit Text und Anh�ngen.
   * @return <b>true </b>, falls der Versand erfolgreich war, ansonsten <b>false
   *         </b>.
   */
  public synchronized boolean sendMail() {
    // Zun�chst davon ausgehen, dass alles klappt.
    boolean finished = true;

    try {
      // System-Umgebungsvariablen holen.
      Properties props = System.getProperties();

      // Kleiner Versuch...
      // props.put("mail.pop3.port", "995");
      // props.put("mail.smtp.starttls.enable","true");
      // props.put("mail.smtp.socketFactory.class",
      // "javax.net.ssl.SSLSocketFactory");
      // props.put("mail.smtp.socketFactory.fallback", "false");

      // SMTP-Host und weiteres merken.
      // if (ssl) {
      // props.put("mail.smtp.socketFactory.class",
      // "javax.net.ssl.SSLSocketFactory");
      // }
      if (smtpHost != null) {
        props.put("mail.smtp.host", smtpHost);
      }
      if (pop3Host != null) {
        props.put("mail.pop3.host", pop3Host);
      }
      if (login != null) {
        props.put("mail.smtp.user", login);
      }
      if (password != null) {
        props.put("mail.smtp.password", password);
      }
      if (smtpPort > 0) {
        props.put("mail.smtp.port", Integer.toString(smtpPort));
        // props.put("mail.smtp.socketFactory.port",
        // Integer.toString(smtpPort));
      }

      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      // props.put("mail.smtp.socketFactory.fallback", "false");

      // Default-Session holen.
      Session session = Session.getDefaultInstance(props, this);

      // Gesamt-Message initialisieren.
      MimeMessage message = new MimeMessage(session);

      // Festlegen, wer diese Mail versendet.
      message.setFrom(new InternetAddress(from));

      // Alle Empf�nger angeben.
      sendTo(message, to, Message.RecipientType.TO);
      sendTo(message, cc, Message.RecipientType.CC);
      sendTo(message, bcc, Message.RecipientType.BCC);

      // Schlie�lich die �berschrift festlegen.
      message.setSubject(subject);

      // Inhalt der Mail in eigener Message angeben.
      BodyPart body = new MimeBodyPart();
      body.setText(text);

      // Der BodyPart ist nur ein Teil des MultiParts.
      Multipart multi = new MimeMultipart();
      multi.addBodyPart(body);

      // In einer Schleife die Attachments hinzuf�gen.
      int anz = att.size();
      for (int i = 0; i < anz; i++) {
        Object attObject = att.get(i);
        if (attObject instanceof File) {
          File file = (File) attObject;
          body = new MimeBodyPart();
          DataSource source = new FileDataSource(file);
          body.setDataHandler(new DataHandler(source));
          body.setFileName(file.getName());
          multi.addBodyPart(body);
        }
      }

      // Gesamt zur Message hinzuf�gen.
      message.setContent(multi);

      // Zu guter letzt die Nachricht versenden.
      Transport.send(message);
    }
    catch (Exception me) {
      me.printStackTrace();
      finished = false;
    }

    // Ergebnis zur�ck geben.
    return finished;
  }

  /**
   * Empf�nger (to, cc, bcc) f�r eine Nachricht festlegen.
   */
  private void sendTo(Message message, Vector<String> v, Message.RecipientType type) {
    try {
      int anz = v.size();
      for (int i = 0; i < anz; i++) {
        Object obj = v.get(i);

        // Wenn es ein String ist, direkt umwandeln, sonst �ber
        // toString()-Methode.
        if (obj instanceof String) {
          message.addRecipient(type, new InternetAddress((String) obj));
        }
        else {
          message.addRecipient(type, new InternetAddress(obj.toString()));
        }
      }
    }
    catch (AddressException exception) {
      throw new IllegalArgumentException(exception);
    }
    catch (MessagingException exception) {
      throw new IllegalArgumentException(exception);
    }
  }

  /**
   * Empf�ngt Nachrichten aus einem E-Mail-Postfach.
   * @param host Host des Postfaches.
   * @param login Login-Name des Postfaches.
   * @param password Passwort f�r das Postfach.
   * @param type Typ des Postfaches ("pop3" oder "imap").
   * @deprecated Nicht veraltert, aber noch nicht fertig; bisher nur ein
   *             Versuchskaninchen!!!
   */
  @Deprecated
  public void getMail(String host, String login, String password, String type) {
    try {
      // Properties vorbereiten und �ndern.
      Properties props = System.getProperties();
      props.put("mail.pop3.host", host);
      Session session = Session.getInstance(props, this);
      Store store = session.getStore(type); // Auch "imap" erlaubt.
      store.connect();
      Folder[] folders = store.getPersonalNamespaces();
      System.out.println("Folders:");
      for (Folder folder : folders) {
        System.out.println("- " + folder.getName() + "  //  " + folder.getFullName());
      }
      Folder folder = store.getFolder("INBOX");
      System.out.println("Folder (Name, FullName):" + folder.getName() + ", " + folder.getFullName());
      folder.open(Folder.READ_ONLY);
      // folder.getUnreadMessageCount();
      Message messages[] = folder.getMessages();
      System.out.println(messages.length + " Messages.");
      System.out.println("");
      int k = messages.length > 8 ? 8 : messages.length;
      for (int i = 0; i < messages.length; i++) {
        // Nur ein paar anlisten.
        if (i == k) {
          i = messages.length - k / 2;
        }
        Message message = messages[i];
        System.out.println(i + ": " + message.getFrom()[0] + "  -  \"" + message.getSubject() + "\"");
        Object content = message.getContent();
        System.out.println("Content-Klasse: " + content.getClass().toString() + " / Content-Type: "
            + message.getContentType());
        @SuppressWarnings("unchecked")
        Enumeration<Header> s = message.getAllHeaders();
        while (s.hasMoreElements()) {
          Header h = s.nextElement();
          System.out.println("H: " + h.getName() + " := " + h.getValue());
        }
        System.out.println(" ");
        if (content instanceof String) {
          System.out.println("String-CONTENT ::: " + (String) content);
        }
        else {
          System.out.println("NO String-CONTENT ::: " + content.getClass());
        }
      }
      folder.close(false);
      store.close();
    }
    catch (MessagingException exception) {
      throw new RuntimeException(exception);
    }
    catch (IOException exception) {
      throw new RuntimeException(exception);
    }
  }

  /**
   * �berschriebene Methode.
   * @return Authentikator f�r Mail-Account-Passwort.
   */
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(login, password);
  }

  /**
   * Print some data on standard output.
   */
  public void print() {
    System.out.println("SMTP: " + smtpHost);
    System.out.println("POP3: " + pop3Host);
    System.out.println("FROM: " + from);
    System.out.println("LOG:  " + login);
    System.out.println("PASS: " + password);
    for (int i = 0; i < to.size(); i++) {
      System.out.println("TO:   " + to.get(i));
    }
    for (int i = 0; i < cc.size(); i++) {
      System.out.println("CC:   " + cc.get(i));
    }
    for (int i = 0; i < bcc.size(); i++) {
      System.out.println("BCC:  " + bcc.get(i));
    }
    System.out.println("TITL: " + subject);
    System.out.println("TEXT: " + text);
  }

  /**
   * @return Liefert das Field <code>login</code>
   */
  public String getLogin() {
    return login;
  }

  /**
   * @param login Setzt das Field <code>login</code>
   */
  public void setLogin(String login) {
    this.login = login;
  }

  /**
   * @return Liefert das Field <code>password</code>
   */
  public String getPassword() {
    return password;
  }

  /**
   * @param password Setzt das Field <code>password</code>
   */
  public void setPassword(String password) {
    this.password = password;
  }

  /**
   * @return Liefert das Field <code>smtpHost</code>
   */
  public String getSmtpHost() {
    return smtpHost;
  }

  /**
   * Set SMTP host and port.
   * @param smtpHost SMTP-Host.
   * @param smtpPort SMTP-Port.
   */
  public void setSmtp(String smtpHost, int smtpPort) {
    setSmtpHost(smtpHost);
    this.smtpPort = smtpPort;
  }

  /**
   * Set SMTP host.
   * @param smtpHost SMTP host adress.
   */
  private void setSmtpHost(String smtpHost) {
    this.smtpHost = smtpHost;
  }

  /**
   * @return Liefert das Field <code>pop3Host</code>
   */
  public String getPop3Host() {
    return pop3Host;
  }

  /**
   * @param pop3Host Setzt das Field <code>pop3Host</code>
   */
  public void setPop3Host(String pop3Host) {
    this.pop3Host = pop3Host;
  }

  /**
   * @return Liefert das Field <code>subject</code>
   */
  public String getSubject() {
    return subject;
  }

  /**
   * @param subject Setzt das Field <code>subject</code>
   */
  public void setSubject(String subject) {
    this.subject = subject;
  }

  /**
   * @return Liefert das Field <code>text</code>
   */
  public String getText() {
    return text;
  }

  /**
   * @param text Setzt das Field <code>text</code>
   */
  public void setText(String text) {
    this.text = text;
  }

  /**
   * @param from Setzt das Field <code>from</code>
   */
  public void setFrom(String from) {
    this.from = from;
    if (from.endsWith("@googlemail.com")) {
      setLogin(from);
      setPop3Host("pop.googlemail.com");
      setSmtp("smtp.googlemail.com", 587);
    }
    else if (from.contains("@gmx.")) {
      setLogin(from);
      setPop3Host("pop.gmx.net");
      setSmtp("mail.gmx.net", 587);
    }
    else if (from.contains("@aol.com")) {
      setLogin(from.substring(0, from.indexOf('@')));
      setPop3Host("pop.aol.com");
      setSmtp("smtp.de.aol.com", 587);
    }
    else if (from.endsWith("@aikq.de")) {
      setLogin(from);
      setPop3Host("aikq.de");
      setSmtp("aikq.de", 25);
    }
  }

  /**
   * @return Liefert das Field <code>from</code>
   */
  public String getFrom() {
    return from;
  }

  /**
   * F�gt einen weiteren Empf�nger hinzu.
   * @param mail Empf�nger.
   */
  public void addTO(String mail) {
    to.add(mail);
  }

  /**
   * F�gt einen weiteren Kopie-Empf�nger hinzu.
   * @param mail Empf�nger.
   */
  public void addCC(String mail) {
    cc.add(mail);
  }

  /**
   * F�gt einen weiteren Blindkopie-Empf�nger hinzu.
   * @param mail Empf�nger.
   */
  public void addBCC(String mail) {
    bcc.add(mail);
  }

  /**
   * L�scht alle Empf�nger.
   */
  public void clearToCcBcc() {
    to.clear();
    cc.clear();
    bcc.clear();
  }

  /**
   * F�gt eine Attachment-Datei hinzu.
   * @param file Datei.
   */
  public void addAttachment(File file) {
    att.add(file);
  }

  /**
   * F�gt eine Attachment-Datei hinzu.
   * @param filename Dateiname.
   */
  public void addAttachment(String filename) {
    addAttachment(new File(filename));
  }
}
TOP

Related Classes of de.chris_soft.fyllgen.utilities.MailTools

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.