Here is an example, if you like:


import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.event.ConnectionEvent; import javax.mail.event.ConnectionListener; import javax.mail.event.TransportEvent; import javax.mail.event.TransportListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.michaelmcgrady.exception.ChainedException;
import com.michaelmcgrady.exception.StackTraceToString;

/********************************************************************
 transport is a simple program that:
   A.  creates a message,

   B.  explicitly retrieves a Transport from the session based on the
       type of the address (it is InternetAddress, so SMTP will be
       used) and

C. sends the message.

usage: java transport "toaddr1[, toaddr2]*" from smtphost true|false

      (1) to = destination email address
      (2) from = origin email address
      (3) smtphost = hostname of the machine that has the smtp server running.
      (4) true|false = debug during sending

 The to addresses can be either a single email address or a
 comma-separated list of email addresses in quotes, i.e.
 "[EMAIL PROTECTED], jane, [EMAIL PROTECTED]". The last parameter either turns
 on or turns off debugging during sending.

 @author Michael McGrady
 ********************************************************************/
public class Send
    implements ConnectionListener,
               TransportListener {
  private   static Log log = LogFactory.getLog(Send.class);

public Send() {}

  public static void send(String to,
                          String from,
                          String subject,
                          String host,
                          String debug,
                          String message)
      throws ChainedException {
    Properties        props = new Properties();
    InternetAddress[] addrs = null;
    boolean           setDebug = false;
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.host", host);
    if (debug.equals("true")) {
      setDebug = true;
    } else if (debug.equals("false")) {
      setDebug = false;
    } else {
      usage();
      return;
    }

    try {
      addrs = InternetAddress.parse(to, false);
    } catch(AddressException ae) {
      throw new ChainedException(ae, "Invalid address: " + ae.getMessage());
    }

    Session session = Session.getInstance(props, null);
    session.setDebug(setDebug);
    Send send = new Send();
    send.send(session, addrs, subject, message, from);
  }

  public void send(Session session,
                 InternetAddress[] toAddr,
                 String subject,
                 String message,
                 String from) {
    Transport trans = null;

    try {
      Message msg = new MimeMessage(session);
      InternetAddress fromAddress = new InternetAddress(from);
      msg.setFrom(fromAddress);
      msg.setRecipients(Message.RecipientType.TO, toAddr);
      msg.setSubject(subject);
      msg.setSentDate(new Date());  // Date: header
      msg.setContent(message, "text/plain");
      msg.saveChanges();
      trans = session.getTransport(toAddr[0]);
      trans.addConnectionListener(this);
      trans.addTransportListener(this);
      trans.connect();
      trans.sendMessage(msg, toAddr);
      try {
        // give the EventQueue enough time to fire its events
        Thread.sleep(5) ;
      } catch(InterruptedException ie) {
      }

    } catch (MessagingException me) {
      // give the EventQueue enough time to fire its events
      try {
        Thread.sleep(5);
      } catch(InterruptedException ie) {
      }

      log.error(StackTraceToString.showStackTrace(me));
      Exception e = me;
      do {
        if (e instanceof SendFailedException) {
          SendFailedException sfex = (SendFailedException)e;
          Address[] invalid = sfex.getInvalidAddresses();
          Address[] validUnsent = sfex.getValidUnsentAddresses();
          Address[] validSent = sfex.getValidSentAddresses();
        }

        if(e instanceof MessagingException) {
          e = ((MessagingException)e).getNextException();
        } else {
          e = null;
        }
      } while(e != null);
    } finally {
      try {
        // close the transport
        trans.close();
      } catch (MessagingException me) {
        log.error(StackTraceToString.showStackTrace(me));
      }
    }
  }

  public void opened(ConnectionEvent e) {
    log.info(">>> ConnectionListener.opened()");
  }

  public void disconnected(ConnectionEvent e) {
    log.info(">>> Connection disconnected");
  }


public void closed(ConnectionEvent e) { log.info(">>> ConnectionListener.closed()"); }

  public void messageDelivered(TransportEvent e) {
    log.info(">>> TransportListener.messageDelivered().");
    log.info(" Valid Addresses:");
    Address[] valid = e.getValidSentAddresses();

    if (valid != null) {
      for (int i = 0; i < valid.length; i++) {
        log.info("    " + valid[i]);
        log.info("The address: " + valid[i] + " was returned as valid");
      }
    }
  }

  public void messageNotDelivered(TransportEvent e) {
    log.info(">>> TransportListener.messageNotDelivered().");
    log.info(" Invalid Addresses:");
    Address[] invalid = e.getInvalidAddresses();
    if (invalid != null) {
      for (int i = 0; i < invalid.length; i++) {
        log.info("    " + invalid[i]);
      }
    }
  }
  public void messagePartiallyDelivered(TransportEvent te) {
    // SMTPTransport doesn't partially deliver msgs
  }

private static void usage() {
log.info("usage: java transport \"<to1>[, <to2>]*\" <from> <smtp> true|false\nexample: java transport \"[EMAIL PROTECTED], jane\" senderaddr smtphost false\nanother example: java com.michaelmcgrady.mail.Send [EMAIL PROTECTED] [EMAIL PROTECTED] smtp.harbornet.com true");
}
} /// 8-)




/***********************************************************
 This class is used to register new users.

 The new users are automatically registered as a "visitor"
 type.  They are given a username and a password on a
 temporary basis, which are a function of the row identity
 number given their data on submission to the database.

 This is emailed for access via logon.  Thus, the user
 cannot get by this page without a username and password
 sent to a working email address.
 ***********************************************************/
public class LogicRegister {
  private static Log log = LogFactory.getLog(LogicRegister.class);

  public ActionForward register(String             name,
                                       String             password,
                                       String             email,
                                       HttpServletRequest request,
                                       ActionMapping      mapping) {

    HttpSession    session       = request.getSession();
    ActionErrors   errors        = new ActionErrors();
    ActionMessages messages      = new ActionMessages();
    String         tmpName       = name; // The temporary name is to make sure
                                         // our username does not include
                                         // noxious elements

    tmpName = massage(tmpName);
    email   = massage(email);

DAOFactory daoFactory = DAOFactory.getDAOFactory(SiteConstant.HSQL_DATABASE);
DAOMail DAOMail = daoFactory.getDAOMail();
DAOUser DAOUser = daoFactory.getDAOUser();
UserCompositeEntity composite = new UserCompositeEntity();
Mail mail = composite.getMailVO();
User user = composite.getUserVO();
User userNULL = composite.getUserVO();


   /********************************************************
    Set the user tmpName (name) and password values from
    the LogonForm and default values for the type (visitor),
    status (temporary) and time (milliseconds since Jan. 1,
    1970).
    ********************************************************/
    user.setName(name);
    user.setEmail(email);
    user.setType(SiteConstant.VISITOR);
    user.setStatus(SiteConstant.TEMPORARY);
    user.setTime(new java.util.Date().getTime());

    userNULL.setUsername(null);
    userNULL.setPassword(null);
    userNULL.setName(name);
    userNULL.setType(SiteConstant.VISITOR);
    userNULL.setStatus(SiteConstant.TEMPORARY);
    userNULL.setTime(new java.util.Date().getTime());

/********************************************************
Insert the user's values with the default values into
the database and get the PRIMARY KEY row identity value.
If something goes wrong, add the errors and save the
errors in request scope via the utility saveErrors
method in this class. Then get the input forward from
the action mapping and use an action forward to forward
to that location.
********************************************************/
int rowIdentity = -99;
try {
// This is to make sure that we don't run into our identity
// condition in the SQL for users, viz. that we cannot
// repeat a combination of username and password. This is
// true even if the username and password are null. So, we
// have to make sure that combination is not present.
DAOUser.deleteUser(userNULL);
rowIdentity = DAOUser.insertUser(user);
} catch(ChainedException ce) {
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.database", ce.getMessage()));
saveErrors(request, errors);
return (new ActionForward("default.welcome"));
}


   /********************************************************
    Clean up the input name for conversion to an initial
    database tmpName and password.
    ********************************************************/
    tmpName  = new StringTokenizer(tmpName," \t\n\r\f\'\"").nextToken();
    password = ("" + rowIdentity + tmpName);
    tmpName  = (tmpName + rowIdentity);

    user.setUsername(tmpName);
    user.setPassword(password);
    user.setId(rowIdentity);

try {
DAOUser.updateUser(user);
} catch(ChainedException ce) {
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.database", ce.getMessage()));
saveErrors(request, errors);
return (new ActionForward("default.welcome"));
}


mail.setPage(SiteConstant.LOGON);
name = user.getName();
try {
mail = DAOMail.findMail(mail);
mail.setSubject("Welcome, " + ((name == null) ? "" : name) + ", here are your temporary username and password.");
} catch(ChainedException ce) {
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.database", ce.getMessage()));
saveErrors(request, errors);
return (new ActionForward("default.welcome"));
}


String message = "username: " + tmpName + "\npassword: " + password;
try {
new Send().send(email, // to
mail.getSender(), // from
mail.getSubject(), // subject
mail.getHost(), // host
mail.getDebug(), // debug
message); // mail message
messages.add("user_added", new ActionMessage("messages.user", name, email));
messages.add("get_email", new ActionMessage("messages.email", email));
saveMessages(request,messages);
return (new ActionForward("default.welcome"));


} catch(ChainedException ce) {
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.database", ce.getMessage()));
saveErrors(request, errors);
return (new ActionForward("default.welcome"));
}
}


 /**********************************************************
  Utility methods: save errors and messages for presentation
  **********************************************************/
  private static void saveErrors(HttpServletRequest request,
                                 ActionErrors       errors) {
    if ((errors == null) || errors.isEmpty()) {
      request.removeAttribute(Globals.ERROR_KEY);
      return;
    }
    request.setAttribute(Globals.ERROR_KEY, errors);
  }

  private static void saveMessages(HttpServletRequest request,
                                   ActionMessages     messages) {
    if ((messages == null) || messages.isEmpty()) {
      request.removeAttribute(Globals.MESSAGE_KEY);
      return;
    }
    request.setAttribute(Globals.MESSAGE_KEY, messages);
  }

  private static String  massage(String input) {
    input = Replace.replace(input,"'","&#039;");
    input = Replace.replace(input,"<","&lt;");
    input = Replace.replace(input,">","&gt;");
    return input;
  }
}




At 08:40 AM 2/19/2004, you wrote:
> From: Jean-Michel Robinet [mailto:[EMAIL PROTECTED]
> After the action is performed, I need to send the html view
> back to the http client and to an email output.
> I am not sure on how to do it.

In the Action, send the email, then forward to the html view (JSP?).

Google should turn up many examples of how to send an email from Java,
if that's the part you're stuck on.  I would put that in a helper class
which gets called from the Action.  That way you can reuse it in other
projects that may not be Struts based.

--
Wendy Smoak
Application Systems Analyst, Sr.
ASU IA Information Resources Management

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



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



Reply via email to