alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code


/**
 *  Transport.java
 *
 *  Bill Lynch
 *  CoolServlets.com
 *  April 21 1999
 *
 *  Email Package Version 1.1
 *
 *    Copyright (C) 1999  Bill Lynch
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Library General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Library General Public License for more details.
 *
 *    You should have received a copy of the GNU Library General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.coolservlets.email;

/**
 *  Transport class
 *
 *  This class is the class that actually sends an email by talking to an SMTP
 *  server.
 *
 *  What's changed in 1.1 (most changes to 1.1 occured in THIS class)
 *    1.  Improved the FROM field a little so that the correct error is thrown if
 *        the FROM is not included. (It's required inorder to send an email.)
 *    2.  Fixed the behavior of the "To" and "Cc" fields. In 1.0, multiple To's
 *        or Cc's would display as multiple copies of the first email address.
 *        There was no problem in sending, just displaying.
 *    3.  Brackets are no longer printed for a single email address:
 *        Before: <bill@coolservlets.com>
 *        After:  bill@coolservlets.com
 *
 *  SMTP documentation (RFC821) can be found at:
 *    http://freesoft.org/CIE/RFC/821/index.htm
 *
 *  This class also checks for errors. An exception is thrown if a connection
 *  to the SMTP server cannot be established.
 *  The message itself must have the FROM and TO fields specified. (Acutally,
 *  to send an email through SMTP, you don't need a FROM field. I decided to
 *  require it to prevent totally anonymous emails. However, you could take
 *  that requirement out if you wanted to.)
 *
 *  Here's how this class should be used:
 *
 *  Message msg = new Message(); // fill this up, ie, FROM, TO's, etc... (see Message class)
 *  Transport tr = new Transport( "yourHost.com", 25 ); // SMTP ports are 25 by default
 *  try
 *   {  tr.send( msg );
 *   }
 *  catch( TransportExeception te )
 *   { }
 *
 *  You should probably do something with the exception instead of ignoring it
 *  like I just did. :)
 *
 *  Public Methods:
 *    Transport()
 *    Transport( String smtpHost, int smtpPort )
 *    String getSmtpHost( )
 *    getSmtpPort( )
 *    void setSmtpHost( String smtpHost )
 *    void setSmtpPort( int smtpPort )
 *    void send( Message msg ) throws TransportException
 *
 *  Private Methods/Fields:
 *    String smtpHost;
 *    int smtpPort;
 *
 */

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *  Transport class
 *
 *  This class
 */

public class Transport
{
  public Transport()
  {}
  /**
   *  Construct a Transport object by specifying a host and port.
   */
  public Transport( String smtpHost, int smtpPort )
  { this.smtpHost = smtpHost;
    this.smtpPort = smtpPort;
  }
  /**
   *  Returns the SMTP host (ie, smtpServer.coolservlets.com).
   */
  public String getSmtpHost( )
  { return smtpHost;
  }
  /**
   *  Returns the SMTP port number (usually 25).
   */
  public int getSmtpPort( )
  { return smtpPort;
  }
  /**
   *  Sets the SMTP host.
   */
  public void setSmtpHost( String smtpHost )
  { this.smtpHost = smtpHost;
  }
  /**
   *  Sets the SMTP port number.
   */
  public void setSmtpPort( int smtpPort )
  { this.smtpPort = smtpPort;
  }

  /**
   *  Sends the message by talking to a SMTP port.
   *
   *  Here's a quick bit of SMTP info (you DON'T need to know this to use this class):
   *
   *    To send an email via SMTP, simply connect to the SMTP server on
   *    port 25. Here's the basic X commands to send an email:
   *    (The ">" lines will be what is written back from the SMTP server)
   *    Also note, that I've removed my own server info with "x"'s
   *
   *    > 220 xxx.xxx.net ESMTP Sendmail 8.9.1/8.9.1; Thu, 1 Apr 1999 12:55:27 -0600 (CST)
   *    HELO yourHost.com
   *    > 250 xxx.xxx.net Hello xxx.xxx.xxx.net [000.000.000.000], pleased to meet you
   *    MAIL FROM: <yourName@yourPlace.com>
   *    > 250 <yourName@yourPlace.com>... Sender ok
   *    RCPT TO: <someoneYouKnow@theirPlace.com>
   *    > 250 <someoneYouKnow@theirPlace.com>... Recipient ok
   *    DATA
   *    > 354 Enter mail, end with "." on a line by itself
   *    From: Your Name <yourName@yourPlace.com>
   *    To: Someone You Know <someoneYouKnow@theirPlace.com>
   *    Subject: Hi There
   *    Hi, how's it going?
   *    Later!
   *    .
   *    > 250 MAA19177 Message accepted for delivery
   *    QUIT
   *
   */
  public void send( Message msg ) throws TransportException
  {
    try
    {
      Socket s = new Socket( this.smtpHost, this.smtpPort );
      PrintWriter out = new PrintWriter( s.getOutputStream() );
      // Successive versions of this class will get feedback from the SMTP server like so:
      // InputStreamReader in = new InputStreamReaders( s.getInputStream() );
      // This will allow for more robust error checking.

      // Say Hi...
      out.println( "HELO " + this.smtpHost );

      // FROM
      Address[] from = msg.getFrom();
      if( from == null || from.length == 0 )
        throw new TransportException( "No \"FROM\" specified." );
      /* added new "else" statement: 1.1 */
      /* This is necessary to make sure that the FROM is included */
      else
      { if( from[0].getAddress() != null && from[0].getAddress().length() > 0 )
         out.println( "MAIL FROM: <" + from[0].getAddress() + ">" );
        else
          throw new TransportException( "No \"FROM\" specified." );
      }

      // TO, CC, BCC (all are added to the recipient list)
      Address[] to = msg.getRecipients( RecipientType.TO );
      if( to == null || to.length == 0 )
        throw new TransportException( "No \"TO\" specified." );
      else
        for( int i=0; i<to.length; i++ )
          out.println( "RCPT TO: <"+ to[i].getAddress() +">" );

      Address[] cc = msg.getRecipients( RecipientType.CC );
      if( cc != null )
        for( int i=0; i<cc.length; i++ )
          out.println( "RCPT TO: <"+ cc[i].getAddress() +">" );

      Address[] bcc = msg.getRecipients( RecipientType.BCC );
      if( bcc != null )
        for( int i=0; i<bcc.length; i++ )
          out.println( "RCPT TO: <"+ bcc[i].getAddress() +">" );


      // Start of data section
      out.println( "DATA" );

      // From:
      if( from != null )
        out.println( "From: "+ ( (from[0].getPersonal() != null) ? from[0].getPersonal()+" " : "" )
                           + "<"+ from[0].getAddress() +">" );

      // To:
      if( to != null && to.length > 0 )
      {
        String line = "To: ";
        for( int i=0; i<to.length; i++ )
        {
          line += ( (to[i].getPersonal()!=null)
                     ? ( to[i].getPersonal() + " <" + to[i].getAddress() + ">" )
                     : ( to[i].getAddress() )
                     );
          if( i < to.length - 1 )
            line += ", ";
        }
        out.println( line );
      }

      // CC:
      if( cc != null && cc.length > 0 )
      {
        String line = "CC: ";
        for( int i=0; i<cc.length; i++ )
        {
          line += ( (cc[i].getPersonal()!=null)
                     ? ( cc[i].getPersonal() + " <" + cc[i].getAddress() + ">" )
                     : ( cc[i].getAddress() )
                     );
          if( i < cc.length - 1 )
            line += ", ";
        }
        out.println( line );
      }

      // Subject:
      if( msg.getSubject() != null )
        out.println( "Subject: "+ msg.getSubject() );

      // The text of the email:
      if( msg.getText() != null )
      { //out.println( new Date() ); // Uncomment for a timestamp in your message!
        out.println( msg.getText() );
      }

      // Signal to the smtp server that we're all done and then quit.
      out.println( "." );
      out.println( "QUIT" );
      out.close();

    }
    catch( IOException ioe )
    { throw new TransportException( "Error connecting to SMTP port." );
    }
  }

  private String smtpHost;
  private int    smtpPort;
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.