Re: how to write a servlet that sends a mail to a particular person
Posted By:
Ed_Hoden
Posted On:
Wednesday, June 26, 2002 07:18 AM
Here is a code fragment of one way to do it. It is based on some code which originally appeared in Java Examples In A Nutshell. I modified it to send HTML-based email.
public void mail() throws Exception
{
if ( Validator.isEmpty( mailHost ) )
{
throw new Exception( "mailHost is null" );
}
if ( Validator.isEmpty( mailEmail ) )
{
throw new Exception( "mailEmail is null" );
}
if ( Validator.isEmpty( subject ) )
{
throw new Exception( "subject is nuull" );
}
System.getProperties().put( "mail.host", mailHost );
URLConnection connection = null;
PrintWriter out = null;
try
{
URL url = new URL( "mailto: " + mailEmail );
connection = url.openConnection();
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
out = new PrintWriter( new OutputStreamWriter( connection.getOutputStream() ) );
out.println( "From: " + fromName + "[" + fromEmail + "]" );
out.println( "To: " + mailName + "[" + mailName + "]" );
out.println( "Subject: " + subject );
out.println( "MIME-Version: 1.0" );
out.println( "Content-Type: text/html; charset=us-ascii" );
out.println( "Content-Transfer-Encoding: 7bit" );
out.println( "Content-Disposition: inline" );
out.println( "Content-Base: " + baseUrl );
out.println();
if ( Validator.isNotEmpty( content ) )
{
out.println( content );
}
} catch( Exception exception ) {
/* do something here */
} finally {
if ( out != null )
{
try
{
out.close();
out = null;
} catch( Exception ignore ) {}
}
}
}