mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

neil_a_wilson
24.02.2007 3b87d717b85d4a4db2697da791efe6a54cf10e87
Add a main method to the org.opends.server.util.EMailMessage class that can be
used to send an e-mail message from the command line.
2 files modified
237 ■■■■■ changed files
opendj-sdk/opends/src/messages/messages/utility.properties 25 ●●●●● patch | view | raw | blame | history
opendj-sdk/opends/src/server/org/opends/server/util/EMailMessage.java 212 ●●●●● patch | view | raw | blame | history
opendj-sdk/opends/src/messages/messages/utility.properties
@@ -423,3 +423,28 @@
INFO_SUBCMDPARSER_OPTIONS_168={options}
INFO_SUBCMDPARSER_SUBCMD_AND_OPTIONS_169={subcommand} {options}
INFO_SUBCMDPARSER_WHERE_OPTIONS_INCLUDE_170=\        where {options} include:
INFO_EMAIL_TOOL_DESCRIPTION_171=Send an e-mail message via SMTP
INFO_EMAIL_HOST_DESCRIPTION_172=The address of the SMTP server to use to send \
 the message
INFO_EMAIL_FROM_DESCRIPTION_173=The address to use for the message sender
INFO_EMAIL_TO_DESCRIPTION_174=The address to use for the message recipient
INFO_EMAIL_SUBJECT_DESCRIPTION_175=The subject to use for the e-mail message
INFO_EMAIL_BODY_DESCRIPTION_176=The path to the file containing the text for \
 the message body
INFO_EMAIL_ATTACH_DESCRIPTION_177=The path to a file to attach to the e-mail \
 message
INFO_EMAIL_HELP_DESCRIPTION_178=Display this usage information
SEVERE_ERR_CANNOT_INITIALIZE_ARGS_179=An error occurred while attempting to \
 initialize the argument parser:  %s
SEVERE_ERR_CANNOT_PARSE_ARGS_180=An error occurred while attempting to parse \
 the provided command-line arguments:  %s
SEVERE_ERR_EMAIL_NO_SUCH_BODY_FILE_181=The file %s specified as the body file \
 for the e-mail message does not exist
SEVERE_ERR_EMAIL_CANNOT_PROCESS_BODY_FILE_182=An error occurred while \
 attempting to process message body file %s:  %s
SEVERE_ERR_EMAIL_NO_SUCH_ATTACHMENT_FILE_183=The attachment file %s does not \
 exist
SEVERE_ERR_EMAIL_CANNOT_ATTACH_FILE_184=An error occurred while trying to \
 attach file %s:  %s
SEVERE_ERR_EMAIL_CANNOT_SEND_MESSAGE_185=An error occurred while trying to \
 send the e-mail message:  %s
opendj-sdk/opends/src/server/org/opends/server/util/EMailMessage.java
@@ -25,14 +25,16 @@
 *      Portions Copyright 2006-2007 Sun Microsystems, Inc.
 */
package org.opends.server.util;
import org.opends.messages.Message;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
@@ -45,13 +47,21 @@
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
import org.opends.server.core.DirectoryServer;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.ArgumentParser;
import org.opends.server.util.args.BooleanArgument;
import org.opends.server.util.args.StringArgument;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.messages.UtilityMessages.*;
import org.opends.messages.MessageBuilder;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
/**
@@ -73,7 +83,7 @@
  // The addresses of the recipients to whom this message should be sent.
  private ArrayList<String> recipients;
  private List<String> recipients;
  // The set of attachments to include in this message.
  private LinkedList<MimeBodyPart> attachments;
@@ -121,7 +131,7 @@
   * @param  recipients  The addresses of the recipients for the message.
   * @param  subject     The subject to use for the message.
   */
  public EMailMessage(String sender, ArrayList<String> recipients,
  public EMailMessage(String sender, List<String> recipients,
                      String subject)
  {
    this.sender     = sender;
@@ -165,7 +175,7 @@
   *
   * @return  The set of recipients for this message.
   */
  public ArrayList<String> getRecipients()
  public List<String> getRecipients()
  {
    return recipients;
  }
@@ -327,6 +337,7 @@
    FileDataSource dataSource = new FileDataSource(attachmentFile);
    attachment.setDataHandler(new DataHandler(dataSource));
    attachment.setFileName(attachmentFile.getName());
    attachments.add(attachment);
  }
@@ -346,9 +357,29 @@
  public void send()
         throws MessagingException
  {
    send(DirectoryServer.getMailServerPropertySets());
  }
  /**
   * Attempts to send this message to the intended recipient(s).  If multiple
   * servers are specified and the first is unavailable, then the other
   * server(s) will be tried before returning a failure to the caller.
   *
   * @param  mailServerPropertySets  A list of property sets providing
   *                                 information about the mail servers to use
   *                                 when sending the message.
   *
   * @throws  MessagingException  If a problem occurred while attempting to send
   *                              the message.
   */
  public void send(List<Properties> mailServerPropertySets)
         throws MessagingException
  {
    // Get information about the available mail servers that we can use.
    MessagingException sendException = null;
    for (Properties props : DirectoryServer.getMailServerPropertySets())
    for (Properties props : mailServerPropertySets)
    {
      // Get a session and use it to create a new message.
      Session session = Session.getInstance(props);
@@ -423,6 +454,8 @@
        {
          multiPart.addBodyPart(attachment);
        }
        message.setContent(multiPart);
      }
@@ -469,5 +502,170 @@
      throw sendException;
    }
  }
  /**
   * Provide a command-line mechanism for sending an e-mail message via SMTP.
   *
   * @param  args  The command-line arguments provided to this program.
   */
  public static void main(String[] args)
  {
    Message description = INFO_EMAIL_TOOL_DESCRIPTION.get();
    ArgumentParser argParser = new ArgumentParser(EMailMessage.class.getName(),
                                                  description, false);
    BooleanArgument showUsage  = null;
    StringArgument  attachFile = null;
    StringArgument  bodyFile   = null;
    StringArgument  host       = null;
    StringArgument  from       = null;
    StringArgument  subject    = null;
    StringArgument  to         = null;
    try
    {
      host = new StringArgument("host", 'h', "host", true, true, true,
                                "{host}", "127.0.0.1", null,
                                INFO_EMAIL_HOST_DESCRIPTION.get());
      argParser.addArgument(host);
      from = new StringArgument("from", 'f', "from", true, false, true,
                                "{address}", null, null,
                                INFO_EMAIL_FROM_DESCRIPTION.get());
      argParser.addArgument(from);
      to = new StringArgument("to", 't', "to", true, true, true, "{address}",
                              null, null, INFO_EMAIL_TO_DESCRIPTION.get());
      argParser.addArgument(to);
      subject = new StringArgument("subject", 's', "subject", true, false, true,
                                   "{subject}", null, null,
                                   INFO_EMAIL_SUBJECT_DESCRIPTION.get());
      argParser.addArgument(subject);
      bodyFile = new StringArgument("bodyfile", 'b', "body", true, true, true,
                                    "{path}", null, null,
                                    INFO_EMAIL_BODY_DESCRIPTION.get());
      argParser.addArgument(bodyFile);
      attachFile = new StringArgument("attachfile", 'a', "attach", false, true,
                                      true, "{path}", null, null,
                                      INFO_EMAIL_ATTACH_DESCRIPTION.get());
      argParser.addArgument(attachFile);
      showUsage = new BooleanArgument("help", 'H', "help",
                                      INFO_EMAIL_HELP_DESCRIPTION.get());
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage);
    }
    catch (ArgumentException ae)
    {
      System.err.println(
           ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()).toString());
      System.exit(1);
    }
    try
    {
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      System.err.println(ERR_CANNOT_PARSE_ARGS.get(ae.getMessage()).toString());
      System.exit(1);
    }
    if (showUsage.isPresent())
    {
      return;
    }
    LinkedList<Properties> mailServerProperties = new LinkedList<Properties>();
    for (String s : host.getValues())
    {
      Properties p = new Properties();
      p.setProperty(SMTP_PROPERTY_HOST, s);
      mailServerProperties.add(p);
    }
    EMailMessage message = new EMailMessage(from.getValue(), to.getValues(),
                                            subject.getValue());
    for (String s : bodyFile.getValues())
    {
      try
      {
        File f = new File(s);
        if (! f.exists())
        {
          System.err.println(ERR_EMAIL_NO_SUCH_BODY_FILE.get(s));
          System.exit(1);
        }
        BufferedReader reader = new BufferedReader(new FileReader(f));
        while (true)
        {
          String line = reader.readLine();
          if (line == null)
          {
            break;
          }
          message.appendToBody(line);
          message.appendToBody("\r\n"); // SMTP says we should use CRLF.
        }
        reader.close();
      }
      catch (Exception e)
      {
        System.err.println(ERR_EMAIL_CANNOT_PROCESS_BODY_FILE.get(s,
                                getExceptionMessage(e)));
        System.exit(1);
      }
    }
    if (attachFile.isPresent())
    {
      for (String s : attachFile.getValues())
      {
        File f = new File(s);
        if (! f.exists())
        {
          System.err.println(ERR_EMAIL_NO_SUCH_ATTACHMENT_FILE.get(s));
          System.exit(1);
        }
        try
        {
          message.addAttachment(f);
        }
        catch (Exception e)
        {
          System.err.println(ERR_EMAIL_CANNOT_ATTACH_FILE.get(s,
                                  getExceptionMessage(e)));
        }
      }
    }
    try
    {
      message.send(mailServerProperties);
    }
    catch (Exception e)
    {
      System.err.println(ERR_EMAIL_CANNOT_SEND_MESSAGE.get(
                              getExceptionMessage(e)));
      System.exit(1);
    }
  }
}