package com.frontiers.server.mail;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 * Sinleton used for easy sending of mail messages. The only
 * configuration needed is that you specify -Dmail.smtp.host=gw.internal.net
 * on your app startup, or otherwise put the value into the system
 * properties.
 *
 * @author Jesse Kuhnert, Coprright 2001 eko systems Inc.
 */
public final class SendMail {
    
    /** Mail session holds data needed to send messages */
    private static Session _session;
    
    /** Not instantiable. Singleton */
    private SendMail(){}
    
    /** Initialize resources */
    public synchronized static void init()
    {
	if (_session == null)
	    _session = Session.getDefaultInstance(System.getProperties(), null);	
    }
    
    /**
     * Sends an e-mail message to the disclosed recipients. Also includes
     * a throwble stack trace string for use in log4j e-mails. 
     *
     * @param String to - Who to send to
     * @param String subject - Subject
     * @param String from - Who it's from
     * @param String location - Location of service sending message
     * @param String throwable - Throwable message
     *
     * @exception SendFailedException - If sending failed
     * @exception MessagingException - If message is invalid
     */
    public static synchronized void sendMessage(String to, String subject, 
						String from, String message, 
						String location, String throwable)
	throws SendFailedException, MessagingException
    {	
	//Formats the message for log4j.
	message = message + "\n\nThrowable Stack Trace:\n" + throwable;
	sendMessage(to, subject, from, message, location);
    }
    
    /**
     * Sends an e-mail message to the disclosed recipients.
     *
     * @param String to - Who to send to
     * @param String subject - Subject
     * @param String from - Who it's from
     * @param String location - Location of service sending message
     *
     * @exception SendFailedException - If sending failed
     * @exception MessagingException - If message is invalid
     */
    public static synchronized void sendMessage(String to, String subject, 
						String from, String message,
						String location)
	throws SendFailedException, MessagingException
    {	
	//Make sure we're initialized
	init();
	
	//Add location to e-mail
	message = message + "\n\nLocation:" + location;
	
	Message msg = new MimeMessage(_session);
	InternetAddress[] toAddrs = null;
	
	toAddrs = InternetAddress.parse(to, false);
	msg.setRecipients(Message.RecipientType.TO, toAddrs);	
	msg.setSubject(subject);	
	msg.setFrom(new InternetAddress(from));	
	msg.setText(message);	

	//Now send it!
	Transport.send(msg);
    }    

}
