charlesb    01/05/11 03:01:25

  Added:       src/java/org/apache/james/transport/mailets
                        AvalonListserv.java AvalonListservManager.java
                        ExceptionThrowingMailet.java Forward.java
                        GenericListserv.java GenericListservManager.java
                        Identity.java LocalDelivery.java
                        NotifyPostmaster.java NotifySender.java Null.java
                        PostmasterAlias.java RemoteDelivery.java
                        ServerTime.java ToProcessor.java ToRepository.java
                        TownAlias.java TownListserv.java
                        UseHeaderRecipients.java
  Removed:     src/org/apache/james/transport/mailets AvalonListserv.java
                        AvalonListservManager.java
                        ExceptionThrowingMailet.java Forward.java
                        GenericListserv.java GenericListservManager.java
                        Identity.java LocalDelivery.java
                        NotifyPostmaster.java NotifySender.java Null.java
                        PostmasterAlias.java RemoteDelivery.java
                        ServerTime.java ToProcessor.java ToRepository.java
                        TownAlias.java TownListserv.java
                        UseHeaderRecipients.java
  Log:
  Moving from src/org to src/java/org
  
  Revision  Changes    Path
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/AvalonListserv.java
  
  Index: AvalonListserv.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.james.*;
  import org.apache.james.services.UsersRepository;
  import org.apache.james.services.UsersStore;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * MailingListServer capability
   *
   * Requires a configuration element in the .conf.xml file of the form:
   *  <repository destinationURL="file://path-to-root-dir-for-repository"
   *              type="USERS"
   *              model="SYNCHRONOUS"/>
   * <membersPath>
   * <membersonly>
   * <attachmentsallowed>
   * <replytolist>
   * <subjectprefix>
   */
  public class AvalonListserv extends GenericListserv {
  
      protected boolean membersOnly = false;
      protected boolean attachmentsAllowed = true;
      protected boolean replyToList = true;
      protected String subjectPrefix = null;
      private UsersRepository members;
  
      public void init() {
          try {
              membersOnly = new 
Boolean(getInitParameter("membersonly")).booleanValue();
          } catch (Exception e) {
          }
          try {
              attachmentsAllowed = new 
Boolean(getInitParameter("attachmentsallowed")).booleanValue();
          } catch (Exception e) {
          }
          try {
              replyToList = new 
Boolean(getInitParameter("replytolist")).booleanValue();
          } catch (Exception e) {
          }
          subjectPrefix = getInitParameter("subjectprefix");
  
          ComponentManager compMgr = 
(ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
          try {
              UsersStore usersStore = 
(UsersStore)compMgr.lookup("org.apache.james.services.UsersStore");
              String repName = getInitParameter("repositoryName");
  
              members = (UsersRepository)usersStore.getRepository( repName );
          } catch (ComponentException cnfe) {
              log("Failed to retrieve Store component:" + cnfe.getMessage());
          } catch (Exception e) {
              log("Failed to retrieve Store component:" + e.getMessage());
          }
      }
  
      public Collection getMembers() throws ParseException {
          Collection reply = new Vector();
          for (Iterator it = members.list(); it.hasNext(); ) {
              reply.add(new MailAddress(it.next().toString()));
          }
          return reply;
      }
  
      public boolean isMembersOnly() {
          return membersOnly;
      }
  
      public boolean isAttachmentsAllowed() {
          return attachmentsAllowed;
      }
  
      public boolean isReplyToList() {
          return replyToList;
      }
  
      public String getSubjectPrefix() {
          return subjectPrefix;
      }
  
      public String getMailetInfo() {
          return "AvalonListserv Mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/AvalonListservManager.java
  
  Index: AvalonListservManager.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.james.*;
  import org.apache.james.services.UsersRepository;
  import org.apache.james.services.UsersStore;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * Adds or removes an email address to a listserv.
   *
   * Sample configuration:
   * <pre>
   * <mailet match="[EMAIL PROTECTED]" 
class="AvalonListservManager">
   *     <membersPath>file://../var/list-james</membersPath>
   * </mailet>
   * </pre>
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class AvalonListservManager extends GenericListservManager {
  
      private UsersRepository members;
  
      public void init() {
          ComponentManager compMgr = 
(ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
          try {
              UsersStore usersStore = (UsersStore) 
compMgr.lookup("org.apache.james.services.UsersStore");
              String repName = getInitParameter("repositoryName");
  
              members = (UsersRepository) usersStore.getRepository(repName);
          } catch (ComponentException cnfe) {
              log("Failed to retrieve Store component:" + cnfe.getMessage());
          } catch (Exception e) {
              log("Failed to retrieve Store component:" + e.getMessage());
          }
      }
  
      public boolean addAddress(MailAddress address) {
          members.addUser(address.toString(), "");
          return true;
      }
  
      public boolean removeAddress(MailAddress address) {
          members.removeUser(address.toString());
          return true;
      }
  
      public boolean existsAddress(MailAddress address) {
          return members.contains(address.toString());
      }
  
      public String getMailetInfo() {
          return "AvalonListservManager Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/ExceptionThrowingMailet.java
  
  Index: ExceptionThrowingMailet.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import javax.mail.*;
  import org.apache.mailet.*;
  
  /**
   * Debugging purpose Mailet. Just throws an exception.
   *
   * @author  Federico Barbieri <[EMAIL PROTECTED]>
   */
  public class ExceptionThrowingMailet extends GenericMailet {
  
      public void service(Mail mail) throws MessagingException {
          throw new MailetException("General protection fault");
      }
  
      public String getMailetInfo() {
          return "ExceptionThrowingMailet Mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/Forward.java
  
  Index: Forward.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  
  /**
   * Replace incoming recipient with specified ones.
   *
   * @author Federico Barbieri <[EMAIL PROTECTED]>
   * @author Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class Forward extends GenericMailet {
  
      private Collection newRecipients;
  
      public void init() throws MessagingException {
          newRecipients = new HashSet();
          StringTokenizer st = new 
StringTokenizer(getMailetConfig().getInitParameter("forwardto"), ",", false);
          while (st.hasMoreTokens()) {
              newRecipients.add(new MailAddress(st.nextToken()));
          }
      }
  
      public void service(Mail mail) throws MessagingException {
          getMailetContext().sendMail(mail.getSender(), newRecipients, 
mail.getMessage());
          mail.setState(Mail.GHOST);
      }
  
      public String getMailetInfo() {
          return "Forward Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/GenericListserv.java
  
  Index: GenericListserv.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.io.*;
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  
  /**
   * An abstract implementation of a listserv.  The underlying implementation must 
define
   * various settings, and can vary in their individual configuration.  Supports 
restricting
   * to members only, allowing attachments or not, sending replies back to the list, 
and an
   * optional subject prefix.
   */
  public abstract class GenericListserv extends GenericMailet {
  
      /**
       * Returns a Collection of MailAddress objects of members to receive this email
       */
      public abstract Collection getMembers() throws MessagingException;
  
      /**
       * Returns whether this list should restrict to senders only
       */
      public abstract boolean isMembersOnly() throws MessagingException;
  
      /**
       * Returns whether this listserv allow attachments
       */
      public abstract boolean isAttachmentsAllowed() throws MessagingException;
  
      /**
       * Returns whether listserv should add reply-to header
       */
      public abstract boolean isReplyToList() throws MessagingException;
  
      /**
       * The email address that this listserv processes on.  If returns null, will use 
the
       * recipient of the message, which hopefully will be the correct email address 
assuming
       * the matcher was properly specified.
       */
      public MailAddress getListservAddress() throws MessagingException {
          return null;
      }
  
      /**
       * An optional subject prefix which will be surrounded by [].
       */
      public abstract String getSubjectPrefix() throws MessagingException;
  
      /**
       * Processes the message.  Assumes it is the only recipient of this forked 
message.
       */
      public final void service(Mail mail) throws MessagingException {
          try {
              Collection members = new Vector();
              members.addAll(getMembers());
  
              //Check for members only flag....
              if (isMembersOnly() && !members.contains(mail.getSender())) {
                  //Need to bounce the message to say they can't send to this list
                  getMailetContext().bounce(mail, "Only members of this listserv are 
allowed to send a message to this address.");
                  mail.setState(Mail.GHOST);
                  return;
              }
  
              //Check for no attachments
              if (!isAttachmentsAllowed() && mail.getMessage().getContent() instanceof 
MimeMultipart) {
                  getMailetContext().bounce(mail, "You cannot send attachments to this 
listserv.");
                  mail.setState(Mail.GHOST);
                  return;
              }
  
              MimeMessage message = mail.getMessage();
  
              //Set the subject if set
              if (getSubjectPrefix() != null) {
                  String prefix = "[" + getSubjectPrefix() + "]";
                  String subj = message.getSubject();
                  //If the "prefix" is in the subject line, remove it and everything 
before it
                  int index = subj.indexOf(prefix);
                  if (index > -1) {
                      if (index == 0) {
                          subj = prefix + ' ' + subj.substring(index + prefix.length() 
+ 1);
                      } else {
                          subj = prefix + ' ' + subj.substring(0, index) + 
subj.substring(index + prefix.length() + 1);
                      }
                  } else {
                      subj = prefix + ' ' + subj;
                  }
  
                  message.setSubject(subj);
              }
              MailAddress listservAddr = getListservAddress();
              if (listservAddr == null) {
                  //Use the recipient
                  listservAddr = (MailAddress)mail.getRecipients().iterator().next();
              }
  
              if (isReplyToList()) {
                  message.setHeader("Reply-To", listservAddr.toString());
              }
  
              //Send the message to the list members
              getMailetContext().sendMail(listservAddr, members, message);
  
              //Kill the old message
              mail.setState(Mail.GHOST);
          } catch (IOException ioe) {
              throw new MailetException("Error creating listserv message", ioe);
          }
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/GenericListservManager.java
  
  Index: GenericListservManager.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.io.*;
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  
  /**
   * An abstract implementation of a listserv manager.  This mailet reads the
   * address to find the command.
   */
  public abstract class GenericListservManager extends GenericMailet {
  
      /**
       * Adds an address to the listserv.  Returns whether command was
       * successful.
       */
      public abstract boolean addAddress(MailAddress address);
  
      /**
       * Removes an address from the listserv.  Returns whether command
       * was successful.
       */
      public abstract boolean removeAddress(MailAddress address);
  
  
      /**
       * Indicates whether an address already exists on the listserv. Returns
       * whether the address exists.
       */
      public abstract boolean existsAddress(MailAddress address);
  
      /**
       * Processes the message.  Checks which command was sent based on the
       * recipient address, and does the appropriate action.
       */
      public final void service(Mail mail) throws MessagingException {
          if (mail.getRecipients().size() != 1) {
              getMailetContext().bounce(mail, "You can only send one command at a time 
to this listserv manager.");
              return;
          }
          MailAddress address = (MailAddress)mail.getRecipients().iterator().next();
          if (address.getUser().endsWith("-off")) {
              if (existsAddress(mail.getSender())) {
                  if (removeAddress(mail.getSender())) {
                      getMailetContext().bounce(mail, "Successfully removed from 
listserv.");
                  } else {
                      getMailetContext().bounce(mail, "You are not subscribed to this 
listserv.");
                  }
              } else {
                  getMailetContext().bounce(mail, "Unable to remove you from listserv 
for some reason");
              }
          } else if (address.getUser().endsWith("-on")) {
              if (existsAddress(mail.getSender())) {
                  getMailetContext().bounce(mail, "You are already subscribed to this 
listserv.");
              } else {
                  if (addAddress(mail.getSender())) {
                      getMailetContext().bounce(mail, "Successfully added to 
listserv.");
                  } else {
                      getMailetContext().bounce(mail, "Unable to add you to the 
listserv for some reason");
                  }
              }
          } else {
              getMailetContext().bounce(mail, "Could not understand the command you 
sent to this listserv manager.\r\n"
                                        + "Valid commands are <listserv>[EMAIL PROTECTED] 
and <listserv>[EMAIL PROTECTED]");
          }
          //Kill the command message
          mail.setState(Mail.GHOST);
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/Identity.java
  
  Index: Identity.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import org.apache.mailet.*;
  
  /**
   * Opposite of Null Mailet. It let any incoming mail untouched. Used only for
   * debugging.
   * @author  Federico Barbieri <[EMAIL PROTECTED]>
   */
  public class Identity extends GenericMailet {
  
      public void service(Mail mail) {
          //Do nothing
      }
  
      public String getMailetInfo() {
          return "Identity Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/LocalDelivery.java
  
  Index: LocalDelivery.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import org.apache.mailet.*;
  import java.util.*;
  import javax.mail.MessagingException;
  
  /**
   * Receive  a Mail from JamesSpoolManager and takes care of delivery
   * the message to local inboxes.
   *
   * @author Federico Barbieri <[EMAIL PROTECTED]>
   * @author Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class LocalDelivery extends GenericMailet {
  
      public void service(Mail mail) throws MessagingException {
          Collection recipients = mail.getRecipients();
          Collection errors = new Vector();
          for (Iterator i = recipients.iterator(); i.hasNext(); ) {
              MailAddress recipient = (MailAddress) i.next();
              try {
                  getMailetContext().storeMail(mail.getSender(), recipient, 
mail.getMessage());
              } catch (Exception ex) {
                  ex.printStackTrace();
                  errors.add(recipient);
              }
          }
          if (errors.isEmpty()) {
              mail.setState(Mail.GHOST);
          } else {
              getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(), 
Mail.ERROR);
              //mail.setRecipients(errors);
              //mail.setState(Mail.ERROR);
              //mail.setErrorMessage("Unable to delivery locally message");
          }
      }
  
      public String getMailetInfo() {
          return "Local Delivery Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/NotifyPostmaster.java
  
  Index: NotifyPostmaster.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.io.*;
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.james.*;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * Sends an error message to the sender of a message (that's typically landed in
   * the error mail repository).  You can optionally specify a sender of the error
   * message.  If you do not specify one, it will use the postmaster's address
   *
   * Sample configuration:
   * <mailet match="All" class="NotifyPostmaster">
   *   <sendingAddress>nobounce@localhost</sendingAddress>
   *   <attachStackTrace>true</attachStackTrace>
   *   <notice>Notice attached to the message (optional)</notice>
   * </mailet>
   *
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   * @author  Ivan Seskar <[EMAIL PROTECTED]>
   */
  public class NotifyPostmaster extends GenericMailet {
      MailAddress notifier = null;
      boolean attachStackTrace = false;
      String noticeText = null;
  
      public void init() throws MessagingException {
          if (getInitParameter("sendingAddress") == null) {
              notifier = getMailetContext().getPostmaster();
          } else {
              notifier = new MailAddress(getInitParameter("sendingAddress"));
          }
          if (getInitParameter("notice") == null) {
              noticeText = "We were unable to deliver the attached message because of 
an error in the mail server.";
          } else {
              noticeText = getInitParameter("notice");
          }
          try {
              attachStackTrace = new 
Boolean(getInitParameter("attachStackTrace")).booleanValue();
          } catch (Exception e) {
          }
      }
  
      /**
       * Sends a message back to the sender indicating what time the server thinks it 
is.
       */
      public void service(Mail mail) throws MessagingException {
          MimeMessage message = mail.getMessage();
          //Create the reply message
          MimeMessage reply = new 
MimeMessage(Session.getDefaultInstance(System.getProperties(), null));
  
          //Create the list of recipients in the Address[] format
          InternetAddress[] rcptAddr = new InternetAddress[1];
          rcptAddr[0] = getMailetContext().getPostmaster().toInternetAddress();
          reply.setRecipients(Message.RecipientType.TO, rcptAddr);
  
          //Set the sender...
          reply.setFrom(notifier.toInternetAddress());
  
          //Create the message
          StringWriter sout = new StringWriter();
          PrintWriter out = new PrintWriter(sout, true);
  
          // First add the "local" notice
          // (either from conf or generic error message)
          out.println(noticeText);
          // And then the message from other mailets
          if (mail.getErrorMessage() != null) {
              out.println();
              out.println("Error message below:");
              out.println(mail.getErrorMessage());
          }
          out.println();
          out.println("Message details:");
  
          if (message.getSubject() != null) {
              out.println("  Subject: " + message.getSubject());
          }
          if (message.getSentDate() != null) {
              out.println("  Sent date: " + message.getSentDate());
          }
          out.println("  MAIL FROM: " + mail.getSender());
          Iterator rcptTo = mail.getRecipients().iterator();
          out.println("  RCPT TO: " + rcptTo.next());
          while (rcptTo.hasNext()) {
              out.println("           " + rcptTo.next());
          }
          Address[] rcpts = message.getFrom();
          if (rcpts != null) {
              out.print("  From: ");
              for (int i = 0; i < rcpts.length; i++) {
                  out.print(rcpts[i] + " ");
              }
              out.println();
          }
          rcpts = message.getRecipients(Message.RecipientType.TO);
          if (rcpts != null) {
              out.print("  To: ");
              for (int i = 0; i < rcpts.length; i++) {
                  out.print(rcpts[i] + " ");
              }
              out.println();
          }
          rcpts = message.getRecipients(Message.RecipientType.CC);
          if (rcpts != null) {
              out.print("  CC: ");
              for (int i = 0; i < rcpts.length; i++) {
                  out.print(rcpts[i] + " ");
              }
              out.println();
          }
          out.println("  Size (in bytes): " + message.getSize());
          if (message.getLineCount() >= 0) {
              out.println("  Number of lines: " + message.getLineCount());
          }
  
  
          try {
              //Create the message body
              MimeMultipart multipart = new MimeMultipart();
              //Add message as the first mime body part
              MimeBodyPart part = new MimeBodyPart();
              part.setContent(sout.toString(), "text/plain");
              part.setHeader("Content-Type", "text/plain");
              multipart.addBodyPart(part);
  
              //Add the original message as the second mime body part
              part = new MimeBodyPart();
              part.setContent(message.getContent(), message.getContentType());
              part.setHeader("Content-Type", message.getContentType());
              multipart.addBodyPart(part);
  
              //if set, attach the full stack trace
              if (attachStackTrace && mail.getErrorMessage() != null) {
                  part = new MimeBodyPart();
                  part.setContent(mail.getErrorMessage(), "text/plain");
                  part.setHeader("Content-Type", "text/plain");
                  multipart.addBodyPart(part);
              }
  
              reply.setContent(multipart);
              reply.setHeader("Content-Type", multipart.getContentType());
          } catch (IOException ioe) {
              throw new MailetException("Unable to create multipart body");
          }
  
          //Create the list of recipients in our MailAddress format
          Set recipients = new HashSet();
          recipients.add(getMailetContext().getPostmaster());
  
          //Set additional headers
          reply.setSubject("Re:" + message.getSubject());
          reply.setHeader("In-Reply-To", message.getMessageID());
  
          //Send it off...
          getMailetContext().sendMail(notifier, recipients, reply);
      }
  
      public String getMailetInfo() {
          return "NotifyPostmaster Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/NotifySender.java
  
  Index: NotifySender.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.io.*;
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.james.*;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * Sends an error message to the sender of a message (that's typically landed in
   * the error mail repository).  You can optionally specify a sender of the error
   * message.  If you do not specify one, it will use the postmaster's address
   *
   * Sample configuration:
   * <mailet match="All" class="NotifyPostmaster">
   *   <sendingAddress>nobounce@localhost</sendingAddress>
   *   <attachStackTrace>true</attachStackTrace>
   *   <notice>Notice attached to the message (optional)</notice>
   * </mailet>
   *
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   * @author  Ivan Seskar <[EMAIL PROTECTED]>
   */
  public class NotifySender extends GenericMailet {
      MailAddress notifier = null;
      boolean attachStackTrace = false;
      String noticeText = null;
  
      public void init() throws MessagingException {
          if (getInitParameter("sendingAddress") == null) {
              notifier = getMailetContext().getPostmaster();
          } else {
              notifier = new MailAddress(getInitParameter("sendingAddress"));
          }
          if (getInitParameter("notice") == null) {
              noticeText = "We were unable to deliver the attached message because of 
an error in the mail server.";
          } else {
              noticeText = getInitParameter("notice");
          }
          try {
              attachStackTrace = new 
Boolean(getInitParameter("attachStackTrace")).booleanValue();
          } catch (Exception e) {
          }
      }
  
      /**
       * Sends a message back to the sender with the message as to why it failed.
       */
      public void service(Mail mail) throws MessagingException {
          MimeMessage message = mail.getMessage();
          //Create the reply message
          MimeMessage reply = new 
MimeMessage(Session.getDefaultInstance(System.getProperties(), null));
  
          //Create the list of recipients in the Address[] format
          InternetAddress[] rcptAddr = new InternetAddress[1];
          rcptAddr[0] = getMailetContext().getPostmaster().toInternetAddress();
          reply.setRecipients(Message.RecipientType.TO, rcptAddr);
  
          //Set the sender...
          reply.setFrom(notifier.toInternetAddress());
  
          //Create the message
          StringWriter sout = new StringWriter();
          PrintWriter out = new PrintWriter(sout, true);
  
          // First add the "local" notice
          // (either from conf or generic error message)
          out.println(noticeText);
          // And then the message from other mailets
          if (mail.getErrorMessage() != null) {
              out.println();
              out.println("Error message below:");
              out.println(mail.getErrorMessage());
          }
          out.println();
          out.println("Message details:");
  
          if (message.getSubject() != null) {
              out.println("  Subject: " + message.getSubject());
          }
          if (message.getSentDate() != null) {
              out.println("  Sent date: " + message.getSentDate());
          }
          Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
          if (rcpts != null) {
              out.print("  To: ");
              for (int i = 0; i < rcpts.length; i++) {
                  out.print(rcpts[i] + " ");
              }
              out.println();
          }
          rcpts = message.getRecipients(Message.RecipientType.CC);
          if (rcpts != null) {
              out.print("  CC: ");
              for (int i = 0; i < rcpts.length; i++) {
                  out.print(rcpts[i] + " ");
              }
              out.println();
          }
          out.println("  Size (in bytes): " + message.getSize());
          if (message.getLineCount() >= 0) {
              out.println("  Number of lines: " + message.getLineCount());
          }
  
  
          try {
              //Create the message body
              MimeMultipart multipart = new MimeMultipart();
              //Add message as the first mime body part
              MimeBodyPart part = new MimeBodyPart();
              part.setContent(sout.toString(), "text/plain");
              part.setHeader("Content-Type", "text/plain");
              multipart.addBodyPart(part);
  
              //Add the original message as the second mime body part
              part = new MimeBodyPart();
              part.setContent(message.getContent(), message.getContentType());
              part.setHeader("Content-Type", message.getContentType());
              multipart.addBodyPart(part);
  
              //if set, attach the full stack trace
              if (attachStackTrace && mail.getErrorMessage() != null) {
                  part = new MimeBodyPart();
                  part.setContent(mail.getErrorMessage(), "text/plain");
                  part.setHeader("Content-Type", "text/plain");
                  multipart.addBodyPart(part);
              }
  
              reply.setContent(multipart);
              reply.setHeader("Content-Type", multipart.getContentType());
          } catch (IOException ioe) {
              throw new MailetException("Unable to create multipart body");
          }
  
          //Create the list of recipients in our MailAddress format
          Set recipients = new HashSet();
          recipients.add(mail.getSender());
  
          //Set additional headers
          reply.setSubject("Re:" + message.getSubject());
          reply.setHeader("In-Reply-To", message.getMessageID());
  
          //Send it off...
          getMailetContext().sendMail(notifier, recipients, reply);
      }
  
      public String getMailetInfo() {
          return "NotifySender Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/Null.java
  
  Index: Null.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import org.apache.mailet.*;
  
  /**
   * Simpliest Mailet which destroy any incoming messages.
   *
   * @author  Federico Barbieri <[EMAIL PROTECTED]>
   */
  public class Null extends GenericMailet {
  
      public void service(Mail mail) {
          mail.setState(mail.GHOST);
      }
  
      public String getMailetInfo() {
          return "Null Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/PostmasterAlias.java
  
  Index: PostmasterAlias.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  //import com.workingdogs.town.*;
  
  /**
   * Rewrites recipient addresses to make sure email for the postmaster is
   * always handles.  This mailet is silently inserted at the top of the root
   * spool processor.  All recipients mapped to postmaster@<servernames> are
   * changed to the postmaster account as specified in the server conf.
   *
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class PostmasterAlias extends GenericMailet {
  
      public void service(Mail mail) throws MessagingException {
          Collection recipients = mail.getRecipients();
          Collection recipientsToRemove = null;
          MailetContext mailetContext = getMailetContext();
          boolean postmasterAddressed = false;
  
          for (Iterator i = recipients.iterator(); i.hasNext(); ) {
              MailAddress addr = (MailAddress)i.next();
              if (addr.getUser().equalsIgnoreCase("postmaster") &&
                  mailetContext.isLocalServer(addr.getHost())) {
                  //Should remove this address... we want to replace it with
                  //  the server's postmaster address
                  if (recipientsToRemove == null) {
                      recipientsToRemove = new Vector();
                  }
                  recipientsToRemove.add(addr);
                  //Flag this as having found the postmaster
                  postmasterAddressed = true;
              }
          }
          if (postmasterAddressed) {
              recipients.removeAll(recipientsToRemove);
              recipients.add(getMailetContext().getPostmaster());
          }
      }
  
      public String getMailetInfo() {
          return "Postmaster aliasing mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/RemoteDelivery.java
  
  Index: RemoteDelivery.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.io.*;
  import java.net.*;
  import java.util.*;
  import javax.mail.MessagingException;
  import javax.mail.Session;
  import javax.mail.Transport;
  import javax.mail.URLName;
  import javax.mail.internet.*;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.configuration.DefaultConfiguration;
  import org.apache.james.*;
  import org.apache.james.core.*;
  import org.apache.james.services.MailServer;
  import org.apache.james.services.MailStore;
  import org.apache.james.services.SpoolRepository;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * Receive  a MessageContainer from JamesSpoolManager and takes care of delivery
   * the message to remote hosts. If for some reason mail can't be delivered
   * store it in the "outgoing" Repository and set an Alarm. After "delayTime" the
   * Alarm will wake the servlet that will try to send it again. After "maxRetries"
   * the mail will be considered underiverable and will be returned to sender.
   *
   * @author Serge Knystautas <[EMAIL PROTECTED]>
   * @author Federico Barbieri <[EMAIL PROTECTED]>
   */
  public class RemoteDelivery extends GenericMailet implements Runnable {
  
      private SpoolRepository outgoing;
      private long delayTime = 21600000; // default is 6*60*60*1000 millis (6 hours)
      private int maxRetries = 5; // default number of retries
      private int deliveryThreadCount = 1; // default number of delivery threads
      private Collection deliveryThreads = new Vector();
      private MailServer mailServer;
  
      public void init() throws MessagingException {
          try {
              delayTime = Long.parseLong(getInitParameter("delayTime"));
          } catch (Exception e) {
          }
          try {
              maxRetries = Integer.parseInt(getInitParameter("maxRetries"));
          } catch (Exception e) {
          }
          ComponentManager compMgr = 
(ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
          String outgoingPath = getInitParameter("outgoing");
          if (outgoingPath == null) {
              outgoingPath = "file:///../var/mail/outgoing";
          }
  
          try {
              // Instantiate the a MailRepository for outgoing mails
              MailStore mailstore = (MailStore) 
compMgr.lookup("org.apache.james.services.MailStore");
  
              DefaultConfiguration spoolConf
                  = new DefaultConfiguration("repository", 
"generated:RemoteDelivery.java");
              spoolConf.addAttribute("destinationURL", outgoingPath);
              spoolConf.addAttribute("type", "SPOOL");
              spoolConf.addAttribute("model", "SYNCHRONOUS");
  
              outgoing = (SpoolRepository) mailstore.select(spoolConf);
          } catch (ComponentException cnfe) {
              log("Failed to retrieve Store component:" + cnfe.getMessage());
          } catch (Exception e) {
              log("Failed to retrieve Store component:" + e.getMessage());
          }
  
          //Start up a number of threads
          try {
              deliveryThreadCount = 
Integer.parseInt(getInitParameter("deliveryThreads"));
          } catch (Exception e) {
          }
          for (int i = 0; i < deliveryThreadCount; i++) {
              Thread t = new Thread(this, "Remote delivery thread (" + i + ")");
              t.start();
              deliveryThreads.add(t);
          }
      }
  
      /**
       * We can assume that the recipients of this message are all going to the same
       * mail server.  We will now rely on the DNS server to do DNS MX record lookup
       * and try to deliver to the multiple mail servers.  If it fails, it should
       * throw an exception.
       *
       * Creation date: (2/24/00 11:25:00 PM)
       * @param Mail org.apache.mailet.Mail
       */
      private void deliver(MailImpl mail, Session session) {
          try {
              log("attempting to deliver " + mail.getName());
              MimeMessage message = mail.getMessage();
              Collection recipients = mail.getRecipients();
              MailAddress rcpt = (MailAddress) recipients.iterator().next();
              String host = rcpt.getHost();
              InternetAddress addr[] = new InternetAddress[recipients.size()];
              int j = 0;
              for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
                  rcpt = (MailAddress)i.next();
                  addr[j] = rcpt.toInternetAddress();
              }
              Exception e = null;
  
              if (addr.length > 0) {
                  //Lookup the possible targets
                  Iterator i = getMailetContext().getMailServers(host).iterator();
                  if (! i.hasNext()) {
                      log("No mail servers found for: " + host);
                  }
                  while ( i.hasNext()) {
                      try {
                          String outgoingmailserver = i.next().toString ();
                          log("attempting delivery of " + mail.getName() + " to host " 
+ outgoingmailserver);
                          URLName urlname = new URLName("smtp://" + 
outgoingmailserver);
  
                          Properties props = session.getProperties();
                          //This was an older version of JavaMail
                          props.put("mail.smtp.user", mail.getSender().toString());
                          props.put("mail.smtp.from", mail.getSender().toString());
                          props.put("mail.debug", "false");
  
                          //Many of these properties are only in later JavaMail 
versions
                          //"mail.smtp.ehlo"  //default true
                          //"mail.smtp.auth"  //default false
                          //"mail.smtp.port"  //default 25
                          //"mail.smtp.dsn.ret"  //default to nothing... appended as 
RET= after MAIL FROM line.
                          //"mail.smtp.dsn.notify" //default to nothing...appended as 
NOTIFY= after RCPT TO line.
                          //"mail.smtp.localhost" //local server name, 
InetAddress.getLocalHost().getHostName();
  
  
                          Transport transport = session.getTransport(urlname);
                          transport.connect();
                          transport.sendMessage(message, addr);
                          transport.close();
                          log("mail (" + mail.getName() + ") sent successfully to " + 
outgoingmailserver);
                          return;
                      } catch (MessagingException me) {
                          log("Exception caught in RemoteDelivery.deliver() : " + me);
                          e = me;
                          /*
                            } catch (java.net.SocketException se) {
                            //Only remember this exception if we received no other 
exception
                            if (e == null) {
                            e = se;
                            }
                            } catch (java.net.UnknownHostException uhe) {
                            //Only remember this exception if we received no other 
exception
                            if (e == null) {
                            e = uhe;
                            }
                          */
                      }
                  }// end while
                  //If we encountered an exception while looping through, send the 
last exception we got
                  if (e != null) {
                      throw e;
                  }
                  throw new MessagingException("No route found to " + host);
              } else {
                  log("no recipients specified... not sure how this could have 
happened.");
              }
          } catch (Exception ex) {
              //We should do a better job checking this... if the failure is a general
              //connect exception, this is less descriptive than more specific SMTP 
command
              //failure... have to lookup and see what are the various Exception
              //possibilities
  
              //Unable to deliver message after numerous tries... fail accordingly
              failMessage(mail, "Delivery failure: " + ex.toString(), ex);
          }
      }
  
      /**
       * Insert the method's description here.
       * Creation date: (2/25/00 1:14:18 AM)
       * @param mail org.apache.mailet.Mail
       * @param reason java.lang.String
       */
      private void failMessage(MailImpl mail, String reason, Exception ex) {
          StringWriter sout = new StringWriter();
          PrintWriter pout = new PrintWriter(sout, true);
          ex.printStackTrace(pout);
          log("Exception delivering mail (" + mail.getName() + ": " + sout.toString());
          if (!mail.getState().equals(Mail.ERROR)) {
              mail.setState(Mail.ERROR);
              mail.setErrorMessage("0");
          }
          int retries = Integer.parseInt(mail.getErrorMessage());
          if (retries >= maxRetries) {
              log("Sending back message " + mail.getName() + " after max (" + retries 
+ ") retries reached");
              try {
                  getMailetContext().bounce(mail, reason);
              } catch (MessagingException me) {
                  log("encountered unexpected messaging exception while bouncing 
message: " + me.getMessage());
              }
          } else {
              //Change the name (unique identifier) of this message... we want to save 
a new copy
              // of it, so change the unique idea for restoring
              mail.setName(mail.getName() + retries);
              log("Storing message " + mail.getName() + " into outgoing after " + 
retries + " retries");
              ++retries;
              mail.setErrorMessage(retries + "");
              outgoing.store(mail);
          }
      }
  
      public String getMailetInfo() {
          return "RemoteDelivery Mailet";
      }
  
      /**
       * For this message, we take the list of recipients, organize these into distinct
       * servers, and duplicate the message for each of these servers, and then call
       * the deliver (messagecontainer) method for each server-specific
       * messagecontainer ... that will handle storing it in the outgoing queue if 
needed.
       *
       * @param mail org.apache.mailet.Mail
       * @return org.apache.mailet.MessageContainer
       */
      public void service(Mail genericmail) throws AddressException {
          MailImpl mail = (MailImpl)genericmail;
  
          //Do I want to give the internal key, or the message's Message ID
          log("Remotely delivering mail " + mail.getName());
          Collection recipients = mail.getRecipients();
  
          //Must first organize the recipients into distinct servers (name made case 
insensitive)
          Hashtable targets = new Hashtable();
          for (Iterator i = recipients.iterator(); i.hasNext();) {
              MailAddress target = (MailAddress)i.next();
              String targetServer = target.getHost().toLowerCase();
              Collection temp = (Collection)targets.get(targetServer);
              if (temp == null) {
                  temp = new Vector();
                  targets.put(targetServer, temp);
              }
              temp.add(target);
          }
  
          //We have the recipients organized into distinct servers... put them into the
          //delivery store organized like this... this is ultra inefficient I think...
  
          //store the new message containers, organized by server, in the outgoing 
mail repository
          String name = mail.getName();
          for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) {
              String host = (String) i.next();
              Collection rec = (Collection)targets.get(host);
              log("sending mail to " + rec + " on " + host);
              mail.setRecipients(rec);
              mail.setName(name + "-to-" + host);
              outgoing.store(mail);
              //Set it to try to deliver (in a separate thread) immediately (triggered 
by storage)
          }
          mail.setState(Mail.GHOST);
      }
  
      public void destroy() {
          //Wake up all threads from waiting for an accept
          notifyAll();
          for (Iterator i = deliveryThreads.iterator(); i.hasNext(); ) {
              Thread t = (Thread)i.next();
              t.interrupt();
          }
      }
  
  
  
      /**
       * Handles checking the outgoing spool for new mail and delivering them if
       * there are any
       */
      public void run() {
          //Checks the pool and delivers a mail message
          Properties props = new Properties();
          Session session = Session.getInstance(props, null);
          while (!Thread.currentThread().interrupted()) {
              try {
                  String key = outgoing.accept(delayTime);
                  log(Thread.currentThread().getName() + " will process mail " + key);
                  MailImpl mail = outgoing.retrieve(key);
                  deliver(mail, session);
                  outgoing.remove(key);
                  mail = null;
              } catch (Exception e) {
                  log("Exception caught in RemoteDelivery.run(): " + e);
              }
          }
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/ServerTime.java
  
  Index: ServerTime.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  import org.apache.james.*;
  import org.apache.james.transport.*;
  
  /**
   * Returns the current time for the mail server.  Sample configuration:
   * <mailet match="[EMAIL PROTECTED]" class="ServerTime">
   * </mailet>
   *
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class ServerTime extends GenericMailet {
      /**
       * Sends a message back to the sender indicating what time the server thinks it 
is.
       */
      public void service(Mail mail) throws javax.mail.MessagingException {
          log("Sending timestamp");
          MimeMessage response = (MimeMessage)mail.getMessage().reply(false);
          response.setSubject("The time is now...");
          response.setText("This mail server thinks it's " + new java.util.Date() + 
".");
  
          Set recipients = new HashSet();
          Address addresses[] = response.getAllRecipients();
          for (int i = 0; i < addresses.length; i++) {
              recipients.add(new MailAddress((InternetAddress)addresses[0]));
          }
  
          MailAddress sender = new MailAddress((InternetAddress)response.getFrom()[0]);
          getMailetContext().sendMail(sender, recipients, response);
      }
  
      public String getMailetInfo() {
          return "ServerTime Mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/ToProcessor.java
  
  Index: ToProcessor.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import org.apache.mailet.*;
  import javax.mail.*;
  
  /**
   * No idea what this class is for..... seems to send processor of a message to
   * another mailet (which I didn't think we were supporting)
   *
   * Sample configuration:
   * <mailet match="All" class="ToProcessor">
   *   <processor>spam</processor>
   *   <notice>Notice attached to the message (optional)</notice>
   * </mailet>
   *
   * @author  Federico Barbieri <[EMAIL PROTECTED]>
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class ToProcessor extends GenericMailet {
      String processor;
      String noticeText = null;
  
      public void init() throws MailetException {
          processor = getInitParameter("processor");
          if (processor == null) {
              throw new MailetException("processor parameter is required");
          }
          noticeText = getInitParameter("notice");
      }
  
      public void service(Mail mail) throws MessagingException {
          log("Sending mail " + mail + " to " + processor);
          mail.setState(processor);
          if (noticeText != null) {
              if (mail.getErrorMessage() == null) {
                  mail.setErrorMessage(noticeText);
              } else {
                  mail.setErrorMessage(mail.getErrorMessage() + "\r\n" + noticeText);
              }
          }
      }
  
  
      public String getMailetInfo() {
          return "ToProcessor Mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/ToRepository.java
  
  Index: ToRepository.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.configuration.DefaultConfiguration;
  import org.apache.james.*;
  import org.apache.james.core.*;
  import org.apache.james.services.MailRepository;
  import org.apache.james.services.MailStore;
  import org.apache.james.transport.*;
  import org.apache.mailet.*;
  
  /**
   * Stores incoming Mail in the specified Repository.
   * If the "passThrough" in confs is true the mail will be returned untouched in
   * the pipe. If false will be destroyed.
   * @version 1.0.0, 24/04/1999
   * @author  Federico Barbieri <[EMAIL PROTECTED]>
   */
  public class ToRepository extends GenericMailet {
  
      private MailRepository repository;
      private boolean passThrough = false;
      private String repositoryPath;
  
      public void init() {
          repositoryPath = getInitParameter("repositoryPath");
          try {
              passThrough = new 
Boolean(getInitParameter("passThrough")).booleanValue();
          } catch (Exception e) {
          }
  
          ComponentManager compMgr = 
(ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
          try {
              MailStore mailstore = (MailStore) 
compMgr.lookup("org.apache.james.services.MailStore");
              DefaultConfiguration mailConf
                  = new DefaultConfiguration("repository", "generated:ToRepository");
              mailConf.addAttribute("destinationURL", repositoryPath);
              mailConf.addAttribute("type", "MAIL");
              mailConf.addAttribute("model", "SYNCHRONOUS");
  
              repository = (MailRepository) mailstore.select(mailConf);
          } catch (ComponentException cnfe) {
              log("Failed to retrieve Store component:" + cnfe.getMessage());
          } catch (Exception e) {
              log("Failed to retrieve Store component:" + e.getMessage());
          }
  
      }
  
      public void service(Mail genericmail) {
          MailImpl mail = (MailImpl)genericmail;
          log("Storing mail " + mail.getName() + " in " + repositoryPath);
          repository.store(mail);
          if (!passThrough) {
              mail.setState(Mail.GHOST);
          }
      }
  
      public String getMailetInfo() {
          return "ToRepository Mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/TownAlias.java
  
  Index: TownAlias.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  import com.workingdogs.town.*;
  
  /**
   * Rewrites recipient addresses based on a database table.  The connection
   * is configured by passing the URL to a conn definition.  You need to set
   * the table name to check (or view) along with the source and target columns
   * to use.  For example,
   * <mailet match="All" class="TownAlias">
   *   <conn>file:///dev/james/dist/var/maildatabase</conn>
   *   <table>MailAlias</table>
   *   <sourceCol>email_alias</sourceCol>
   *   <targetCol>email_address</targetCol>
   * </mailet>
   *
   * @author  Serge Knystautas <[EMAIL PROTECTED]>
   */
  public class TownAlias extends GenericMailet {
      private String conndef = null;
      private String tableName = null;
      private String sourceColumn = null;
      private String targetColumn = null;
  
      public void init() {
          conndef = getInitParameter("conn");
          tableName = getInitParameter("table");
          sourceColumn = getInitParameter("sourceCol");
          targetColumn = getInitParameter("targetCol");
      }
  
      public void service(Mail mail) throws MessagingException {
          Collection recipients = mail.getRecipients();
          String inClause = null;
          for (Iterator i = recipients.iterator(); i.hasNext(); ) {
              if (inClause == null) {
                  inClause = "'" + i.next().toString() + "'";
              } else {
                  inClause += ",'" + i.next().toString() + "'";
              }
          }
          if (inClause == null) {
              return;
          }
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conndef), 
tableName);
              tds.setWhere(sourceColumn + " IN (" + inClause + ")");
              for (int i = 0; i < tds.size(); i++) {
                  Record rec = tds.getRecord(i);
                  MailAddress source = new MailAddress(rec.getAsString(sourceColumn));
                  if (recipients.contains(source)) {
                      MailAddress target = new 
MailAddress(rec.getAsString(targetColumn));
                      recipients.remove(source);
                      recipients.add(target);
                  }
              }
          } catch (TownException te) {
              throw new MailetException("Error accessing database", te);
          }
      }
  
      public String getMailetInfo() {
          return "Town (database) aliasing mailet";
      }
  }
  
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/TownListserv.java
  
  Index: TownListserv.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import org.apache.mailet.*;
  import com.workingdogs.town.*;
  
  /**
   * Database driven listserv.  Queries the database everytime so you do not need
   * to restart mail server for changes to take effect.
   *
   * Parameters:
   * - conn : the connection definition URL
   * - listserv_id : the unique identifier for this listserv in the database
   * - listserv_table : the table that contains the listserv definitions
   * - members_table : the table that contains the list of members for each listserv
   */
  public class TownListserv extends GenericListserv {
  
      String conn = null;
      String listservID = null;
      String listservTable = null;
      String membersTable = null;
  
      public void init() {
          conn = getInitParameter("conn");
          listservID = getInitParameter("listserv_id");
          listservTable = getInitParameter("listserv_table");
          membersTable = getInitParameter("members_table");
      }
  
      public Collection getMembers() throws MessagingException {
          Collection members = new Vector();
          try {
              System.err.println("using table: " + membersTable);
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
membersTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              for (int i = 0; i < tds.size(); i++) {
                  MailAddress addr = new 
MailAddress(tds.getRecord(i).getAsString("member"));
                  members.add(addr);
              }
          } catch (TownException te) {
              throw new MailetException("error retrieving list of members", te);
          }
          return members;
      }
  
      public boolean isMembersOnly() throws MessagingException {
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
listservTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              return tds.getRecord(0).getAsBoolean("members_only");
          } catch (TownException te) {
              throw new MailetException("error retrieving members_only flag", te);
          }
      }
  
      public boolean isAttachmentsAllowed() throws MessagingException {
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
listservTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              return tds.getRecord(0).getAsBoolean("attachments_allowed");
          } catch (TownException te) {
              throw new MailetException("error retrieving is_attachments_allowed 
flag", te);
          }
      }
  
      public boolean isReplyToList() throws MessagingException {
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
listservTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              return tds.getRecord(0).getAsBoolean("reply_to_list");
          } catch (TownException te) {
              throw new MailetException("error retrieving reply_to_list flag", te);
          }
      }
  
      public String getSubjectPrefix() throws MessagingException {
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
listservTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              return tds.getRecord(0).getAsString("subject_prefix");
          } catch (TownException te) {
              throw new MailetException("error retrieving subject prefix", te);
          }
      }
  
      public MailAddress getListservAddress() throws MessagingException {
          try {
              TableDataSet tds = new TableDataSet(ConnDefinition.getInstance(conn), 
listservTable);
              tds.setWhere("listserv_id = '" + listservID + "'");
              return new MailAddress(tds.getRecord(0).getAsString("list_address"));
          } catch (TownException te) {
              throw new MailetException("error retrieving listserv address", te);
          }
      }
  
      public String getMailetInfo() {
          return "TownListserv Mailet";
      }
  }
  
  
  
  1.1                  
jakarta-james/src/java/org/apache/james/transport/mailets/UseHeaderRecipients.java
  
  Index: UseHeaderRecipients.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.transport.mailets;
  
  import org.apache.mailet.*;
  import java.util.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  
  /**
   * <p>Mailet designed to process the recipients from the mail headers rather
   * than the recipients specified in the SMTP message header.  This can be
   * useful if your mail is redirected on-route by a mail server that
   * substitutes a fixed recipient address for the original.</p>
   *
   * <p>To use this, match against the redirection address using the
   * <code>RecipientIs</code> matcher and set the mailet 'class' to
   * <code>UseHeaderRecipients</code>.  This will cause the email to be
   * re-injected into the root process with the recipient substituted
   * by all the recipients in the Mail-For, To and Cc headers
   * of the message.</p>
   *
   * <p>e.g.</p>
   * <pre>
   *    <mailet match="RecipientIs=forwarded@myhost"
   *            class="UseHeaderRecipients">
   *    </mailet>
   * </pre>
   *
   * @version 1.0.0, 24/11/2000
   * @author Stuart Roebuck <[EMAIL PROTECTED]>
   */
  public class UseHeaderRecipients extends GenericMailet {
  
      /**
       * Process an incoming email, removing the currently identified
       * recipients and replacing them with the recipients indicated in
       * the Mail-For, To and Cc headers of the actual email.
       *
       * @param mail incoming email
       */
      public void service(Mail mail) throws MessagingException {
          MimeMessage message = mail.getMessage();
  
          // Utilise features of Set Collections such that they automatically
          // ensure that no two entries are equal using the equality method
          // of the element objects.  MailAddress objects test equality based
          // on equivalent but not necessarily visually identical addresses.
          Collection recipients = mail.getRecipients();
          // Wipe all the exist recipients
          recipients.clear();
          recipients.addAll(getHeaderMailAddresses(message, "Mail-For"));
          if (recipients.isEmpty()) {
              recipients.addAll(getHeaderMailAddresses(message, "To"));
              recipients.addAll(getHeaderMailAddresses(message, "Cc"));
          }
          log("All recipients = " + recipients.toString());
  
          log("Reprocessing mail using recipients in message headers");
          // Return email to the "root" process.
          getMailetContext().sendMail(mail.getSender(), mail.getRecipients(), 
mail.getMessage());
          mail.setState(Mail.GHOST);
      }
  
  
      public String getMailetInfo() {
          return "UseHeaderRecipients Mailet";
      }
  
      /**
       * Work through all the headers of the email with a matching name and
       * extract all the mail addresses as a collection of addresses.
       *
       * @param mail the mail message to read
       * @param name the header name as a String
       * @return the collection of MailAddress objects.
       */
      private Collection getHeaderMailAddresses(MimeMessage message, String name) 
throws MessagingException {
          log("Checking " + name + " headers");
          Collection addresses = new Vector();
          String[] headers = message.getHeader(name);
          String addressString;
          InternetAddress iAddress;
          if (headers != null) {
              for(int i = 0; i < headers.length; i++) {
                  StringTokenizer st = new StringTokenizer(headers[i], ",", false);
                  while (st.hasMoreTokens()) {
                      addressString = st.nextToken();
                      iAddress = new InternetAddress(addressString);
                      log("Address = " + iAddress.toString());
                      addresses.add(new MailAddress(iAddress));
                  }
              }
          }
          return addresses;
      }
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to